您现在的位置是:网站首页> Go语言
Go电子秤代码
- Go语言
- 2020-11-20
- 803人已阅读
摘要
package main import ( "bytes" "errors" "fmt" "html/template" "net" "net/http" "runtime" //"syscall" // "unicode/utf8" "unsafe" "golang.org/x/net/websocket" //"code.google.com/p/go.net/websocket" //"log" "bufio" // "io" "strings" "time" "sync" "encoding/json" "strconv" "LocalWeb/mylib" "math/rand" "os" // "github.com/axgle/mahonia" "github.com/tarm/serial" "reflect" "io/ioutil" "golang.org/x/text/encoding/simplifiedchinese" "golang.org/x/text/transform" ) // 端口 const ( HTTP_PORT string = "888" HTTPS_PORT string = "443" ) // 目录 const ( CSS_CLIENT_PATH = "/css/" CSS2_CLIENT_PATH = "/assets/css/" DART_CLIENT_PATH = "/js/" IMAGE_CLIENT_PATH = "/image/" CSS_SVR_PATH = "web" CSS2_SVR_PATH = "web" DART_SVR_PATH = "web" IMAGE_SVR_PATH = "web" ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) } /* h := syscall.MustLoadDLL("kernel32.dll") c := h.MustFindProc("GetDiskFreeSpaceExW") lpFreeBytesAvailable := int64(0) lpTotalNumberOfBytes := int64(0) lpTotalNumberOfFreeBytes := int64(0) r2, _, err := c.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("F:"))), uintptr(unsafe.Pointer(&lpFreeBytesAvailable)), uintptr(unsafe.Pointer(&lpTotalNumberOfBytes)), uintptr(unsafe.Pointer(&lpTotalNumberOfFreeBytes))) if r2 != 0 { log.Println(r2, err, lpFreeBytesAvailable/1024/1024) } package main import ( "fmt" "syscall" "unsafe" "strconv" ) type ulong int32 type ulong_ptr uintptr type PROCESSENTRY32 struct { dwSize ulong cntUsage ulong th32ProcessID ulong th32DefaultHeapID ulong_ptr th32ModuleID ulong cntThreads ulong th32ParentProcessID ulong pcPriClassBase ulong dwFlags ulong szExeFile [260]byte } func main() { kernel32 := syscall.NewLazyDLL("kernel32.dll"); CreateToolhelp32Snapshot := kernel32.NewProc("CreateToolhelp32Snapshot"); pHandle,_,_ := CreateToolhelp32Snapshot.Call(uintptr(0x2),uintptr(0x0)); if int(pHandle)==-1 { return; } Process32Next := kernel32.NewProc("Process32Next"); for { var proc PROCESSENTRY32; proc.dwSize = ulong(unsafe.Sizeof(proc)); if rt,_,_ := Process32Next.Call(uintptr(pHandle),uintptr(unsafe.Pointer(&proc)));int(rt)==1 { fmt.Println("ProcessName : "+string(proc.szExeFile[0:])); fmt.Println("ProcessID : "+strconv.Itoa(int(proc.th32ProcessID))); }else{ break; } } CloseHandle := kernel32.NewProc("CloseHandle"); _,_,_ = CloseHandle.Call(pHandle); lpBuffer := make([]byte,256) _,_,callErr := syscall.Syscall(_GetLogicalDriveStrings,2,uintptr(len(lpBuffer)),uintptr(unsafe.Pointer(&lpBuffer[0])),0) if callErr != 0 { fmt.Println("callErr", callErr) } disk := []string{} for _,v := range lpBuffer{ if v >= 65 && v <= 90{ disk = append(disk,string(v)+":") } } return disk } import "websocket" type T struct { Msg string Count int } // receive JSON type T var data T websocket.JSON.Receive(ws, &data) // send JSON type T websocket.JSON.Send(ws, data) var mutex sync.Mutex func write() { mutex.Lock() defer mutex.Unlock() 在Go语言中,读写锁由结构体类型sync.RWMutex代表。与互斥锁类似,sync.RWMutex类型的零值就已经是立即可用的读写锁了。在此类型的方法集合中包含了两对方法,即: 代码如下: func (*RWMutex) Lock func (*RWMutex) Unlock 和 复制代码 代码如下: func (*RWMutex) RLock func (*RWMutex) RUnlock */ type ComDeviceData struct { Weight string //重量 UnitPrice string //单价 TotalPrice string //总价 } type WebSocketData struct { Command string //命令 DeviceType string //设备类型 DeviceUuid string //设备唯一id DeviceInfo interface{} //设备信息 Data interface{} //命令数据 } type BindEventST struct { EventName string } type OneWebSocket struct { //一个WebSocket连接 m_RW sync.RWMutex } type oneEvent struct { //一个事件 EventName string //事件名 EventMemo string //事件描述 } type DeviceEventST struct { //一种设备类型的事件 DeviceType string //设备类型 EventArray []oneEvent //设备事件 } type WebSocketEventLink struct { EventLinkArray map[*websocket.Conn]OneWebSocket } type OneDeviceWork struct { Command string SendString string conn *websocket.Conn } type COMWeight struct { m_ComDeviceData ComDeviceData } //设备描述 type NETDevice struct { DeviceCommType string //设备通讯方式 DeviceType string //设备类型 DeviceUuid string //设备唯一id DeviceEvent DeviceEventST //设备事件描 m_EventMAP map[string]WebSocketEventLink //*websocket.Conn //绑定的事件连接 DeviceInfo interface{} //设备信息 LinkOBJ interface{} //设备连接对象 //DeviceWorkPtr []OneDeviceWork } type COMDeviceInfo struct { COMString string //串口信息 } type TCPDeviceInfo struct { IP string //IP地址 nPort int //端口 } type ReturnMessage struct { OK bool //是否成功 Msg string //消息串 MsgData interface{} } type OnePLU struct { PLUNum string //PLU编号 GoodName string //品名 GoodNum string //商品编号 Price string //单价 GoodType string //购买模式 Weight string //皮重 ShopNo string //店号 } type ReportOneRecord struct { RecordNum string //记录号 RecordTime string //记录时间 DeptNo string //部门号 ShopNo string //店号 PLUNum string //PLU序 Weight string //重量 Price string //单价 Total string //折扣前总价 DiscountTotal string //折扣后总价 BalanceNum string //秤号 } var m_LinkRW sync.RWMutex var m_DeviceRW sync.RWMutex var m_LinkUserMap map[*websocket.Conn]OneWebSocket var m_DeviceTypeEventMap map[string]DeviceEventST //设备类型事件数组 var m_DeviceMap map[string]NETDevice //设备列表 //var m_WebSocketData WebSocketData var sGlobalCOM string = "" var sDeviceType string = "" var m_NETDeviceArray []NETDevice var bGlobalVisual bool = false var bGlobalSearchDevice = false var m_SearchRW sync.RWMutex var sGlobalTCPDeviceTypeArray []string = []string{} var nGlobalTCPPortArray []int = []int{} var sGlobalTCPIPArray []string = []string{} var m_GlobalWG sync.WaitGroup func Substr(str string, start, length int) string { rs := []rune(str) rl := len(rs) end := 0 if start < 0 { start = rl - 1 + start } end = start + length if start > end { start, end = end, start } if start < 0 { start = 0 } if start > rl { start = rl } if end < 0 { end = 0 } if end > rl { end = rl } str0 := string(rs[start:end]) rs = nil return str0 } func ChuLiWeight(w string) string { nL := len(w) if nL == 3 { return "0." + w } return Substr(w, 0, nL-3) + "." + Substr(w, nL-3, 3) } func ChuLiUnitPrice(w string) string { nL := len(w) if nL == 2 { return "0." + w } return Substr(w, 0, nL-2) + "." + Substr(w, nL-2, 2) } func ChuLiTotalPrice(w string) string { nL := len(w) if nL == 2 { return "0." + w } return Substr(w, 0, nL-2) + "." + Substr(w, nL-2, 2) } func MyCOMReturn(m_OneDevice NETDevice, Weight string, UnitPrice string, TotalPrice string) bool { var m_WebSocketData WebSocketData var m_ComDeviceData ComDeviceData m_ComDeviceData.Weight = Weight m_ComDeviceData.UnitPrice = UnitPrice m_ComDeviceData.TotalPrice = TotalPrice m_WebSocketData.Command = "COM" m_WebSocketData.Data = m_ComDeviceData m_LinkRW.Lock() for key, _ := range m_LinkUserMap { if err := websocket.JSON.Send(key, m_WebSocketData); err != nil { break } else { } } m_LinkRW.Unlock() return true } func MyCOMReturnEvent(m_OneDevice NETDevice, EventName string, m_WebSocketData WebSocketData) bool { m_LinkRW.Lock() m_WebSocketEventLink, bOK := m_OneDevice.m_EventMAP[EventName] if bOK { for key, _ := range m_WebSocketEventLink.EventLinkArray { if err := websocket.JSON.Send(key, m_WebSocketData); err != nil { break } else { } } } else { fmt.Println("未找到绑定事件", EventName, m_OneDevice.m_EventMAP) } m_LinkRW.Unlock() return true } func FindManyCOMDevice() ([]string, []string) { var sDeviceTypeArray []string = []string{} var sDeviceCOMArray []string = []string{} if bGlobalVisual { sDeviceTypeArray = append(sDeviceTypeArray, "ACS-15Ab") sDeviceCOMArray = append(sDeviceCOMArray, "COM1") return sDeviceTypeArray, sDeviceCOMArray } var s *serial.Port var err error var i int = 1 var n int var sCOM string buf := make([]byte, 1024) var nPos int = 0 var ss string var stringLength int var nn int var tBegin int64 for { sCOM = "COM" + strconv.Itoa(i) c := &serial.Config{Name: sCOM, Baud: 9600} s, err = serial.OpenPort(c) if err != nil { } else { time.Sleep(500000000) tBegin = time.Now().Unix() for { if time.Now().Unix()-tBegin > 1 { fmt.Println("超时退出") break } n, err = s.Read(buf[nPos:]) if err != nil { //log.Fatal(err) break } if n > 0 { nPos += n JXX: if nPos > 2 { if buf[0] == 0x0a && buf[1] == 0x0d { ss = string(buf[2:nPos]) stringLength = len(ss) nn = strings.IndexAny(ss, "\r\n") if nn == -1 { switch stringLength { case 5: //s.Close() //return "ACS-15Ab", sCOM sDeviceTypeArray = append(sDeviceTypeArray, "ACS-15Ab") sDeviceCOMArray = append(sDeviceCOMArray, sCOM) break case 20: //s.Close() //return "ACS-15Ab", sCOM sDeviceTypeArray = append(sDeviceTypeArray, "ACS-15Ab") sDeviceCOMArray = append(sDeviceCOMArray, sCOM) break default: nPos = 0 continue } } else { sss := Substr(ss, 0, nn) stringLength = len(sss) switch stringLength { case 5: //s.Close() //return "ACS-15Ab", sCOM sDeviceTypeArray = append(sDeviceTypeArray, "ACS-15Ab") sDeviceCOMArray = append(sDeviceCOMArray, sCOM) break case 20: //s.Close() //return "ACS-15Ab", sCOM sDeviceTypeArray = append(sDeviceTypeArray, "ACS-15Ab") sDeviceCOMArray = append(sDeviceCOMArray, sCOM) break default: nPos = 0 continue } } //s.Close() //return "ACS-15Ab", sCOM sDeviceTypeArray = append(sDeviceTypeArray, "ACS-15Ab") sDeviceCOMArray = append(sDeviceCOMArray, sCOM) break } else { ss = string(buf[0:nPos]) nn = strings.IndexAny(ss, "\r\n") if nn == -1 { nPos = 0 } else { copy(buf, buf[nn:nPos]) nPos = nPos - nn goto JXX } } } } time.Sleep(200000000) } s.Close() } i = i + 1 if i > 20 { break } } return sDeviceTypeArray, sDeviceCOMArray } func FindCOMDevice() (string, string) { if bGlobalVisual { return "ACS-15Ab", "COM1" } var s *serial.Port var err error var i int = 1 var n int var sCOM string buf := make([]byte, 1024) var nPos int = 0 var ss string var stringLength int var nn int var tBegin int64 for { sCOM = "COM" + strconv.Itoa(i) fmt.Println("扫串口:", sCOM) c := &serial.Config{Name: sCOM, Baud: 9600} s, err = serial.OpenPort(c) if err != nil { fmt.Println("打开失败:", sCOM) } else { fmt.Println("打开成功:", sCOM) time.Sleep(500000000) tBegin = time.Now().Unix() fmt.Println("开始试探串口数据") for { if time.Now().Unix()-tBegin > 1 { fmt.Println("探测数据超时退出") break } n, err = s.Read(buf[nPos:]) if err != nil { //log.Fatal(err) break } if n > 0 { nPos += n JXX: if nPos > 2 { if buf[0] == 0x0a && buf[1] == 0x0d { ss = string(buf[2:nPos]) stringLength = len(ss) nn = strings.IndexAny(ss, "\r\n") if nn == -1 { switch stringLength { case 5: s.Close() return "ACS-15Ab", sCOM case 20: s.Close() return "ACS-15Ab", sCOM default: nPos = 0 continue } } else { sss := Substr(ss, 0, nn) stringLength = len(sss) switch stringLength { case 5: s.Close() return "ACS-15Ab", sCOM case 20: s.Close() return "ACS-15Ab", sCOM default: nPos = 0 continue } } s.Close() return "ACS-15Ab", sCOM } else { ss = string(buf[0:nPos]) nn = strings.IndexAny(ss, "\r\n") if nn == -1 { nPos = 0 } else { copy(buf, buf[nn:nPos]) nPos = nPos - nn goto JXX } } } } time.Sleep(200000000) } s.Close() } i = i + 1 if i > 20 { break } } return "", "" } func MyCOM(call func(m_OneDevice NETDevice, EventName string, m_WebSocketData WebSocketData) bool, m_OneDevice NETDevice) { //fmt.Printf("启动串口\r\n") //m_OneDevice.DeviceWorkPtr = []OneDeviceWork{} var err error var s *serial.Port c := &serial.Config{Name: sGlobalCOM /*"COM4"*/, Baud: 9600} s, err = serial.OpenPort(c) if err != nil { } else { m_OneDevice.LinkOBJ = s } buf := make([]byte, 1024) var nPos int = 0 var nn int = 0 var ss string var m_WebSocketData WebSocketData m_WebSocketData.DeviceInfo = m_OneDevice.DeviceInfo m_WebSocketData.DeviceType = m_OneDevice.DeviceType m_WebSocketData.DeviceUuid = m_OneDevice.DeviceUuid var m_ComDeviceData ComDeviceData var stringWeight string = "0.000" //固定三位小数 var stringUnitPrice string = "0.00" //固定两位小数 var stringTotalPrice string = "0.00" //固定两位小数 if bGlobalVisual { m_OneDevice.LinkOBJ = nil tt := time.Now().Unix() r := rand.New(rand.NewSource(time.Now().UnixNano())) var ww int = 0 for { if time.Now().Unix()-tt >= 1 { ww = r.Intn(10) stringWeight = strconv.Itoa(ww) stringUnitPrice = "0.02" stringTotalPrice = strconv.FormatFloat(float64(ww)*0.02, 'f', 2, 64) tt = time.Now().Unix() } if !bGlobalVisual { break } if bGlobalSearchDevice { break } m_ComDeviceData.Weight = stringWeight m_ComDeviceData.UnitPrice = stringUnitPrice m_ComDeviceData.TotalPrice = stringTotalPrice m_WebSocketData.Command = "onCOMData" m_WebSocketData.Data = m_ComDeviceData //fmt.Println("触发模拟重量") call(m_OneDevice, "onCOMData", m_WebSocketData) time.Sleep(300000000) } } else { for { if err != nil { //log.Fatal(err) //fmt.Println("%v", err) m_OneDevice.LinkOBJ = nil return } else { /* n, err := s.Write([]byte("P")) if err != nil { //log.Fatal(err) return } */ n, err := s.Read(buf[nPos:]) if err != nil { //log.Fatal(err) return } if bGlobalSearchDevice { s.Close() fmt.Println("关闭退出") return } if n > 0 { nPos += n //fmt.Printf("收串口数据%d\r\n", n) //log.Print("%q", buf[:n]) JX: if nPos > 2 { stringWeight = "0" stringUnitPrice = "0" stringTotalPrice = "0" //fmt.Printf("action data %v\r\n", buf) if buf[0] == 0x0a && buf[1] == 0x0d { ss = string(buf[2:nPos]) //fmt.Println("串口数据:", ss) stringLength := len(ss) nn = strings.IndexAny(ss, "\r\n") if nn == -1 { switch stringLength { case 5: nPos = 0 stringWeight = ss stringUnitPrice = "0" stringTotalPrice = "0" case 20: stringWeight = Substr(ss, 0, 5) stringUnitPrice = Substr(ss, 7, 5) stringTotalPrice = Substr(ss, 14, 6) default: nPos = 0 continue } stringWeight = ChuLiWeight(stringWeight) stringUnitPrice = ChuLiUnitPrice(stringUnitPrice) stringTotalPrice = ChuLiTotalPrice(stringTotalPrice) fmt.Printf("收解析数据stringWeight:%v,stringUnitPrice:%v,stringTotalPrice:%v\r\n", stringWeight, stringUnitPrice, stringTotalPrice) m_ComDeviceData.Weight = stringWeight m_ComDeviceData.UnitPrice = stringUnitPrice m_ComDeviceData.TotalPrice = stringTotalPrice m_WebSocketData.Command = "onCOMData" m_WebSocketData.Data = m_ComDeviceData call(m_OneDevice, "onCOMData", m_WebSocketData) } else { sss := Substr(ss, 0, nn) stringLength = len(sss) switch stringLength { case 5: nPos = 0 stringWeight = sss stringUnitPrice = "0" stringTotalPrice = "0" case 20: stringWeight = Substr(sss, 0, 5) stringUnitPrice = Substr(sss, 7, 5) stringTotalPrice = Substr(sss, 14, 6) default: nPos = 0 continue } stringWeight = ChuLiWeight(stringWeight) stringUnitPrice = ChuLiUnitPrice(stringUnitPrice) stringTotalPrice = ChuLiTotalPrice(stringTotalPrice) fmt.Printf("收解析数据stringWeight:%v,stringUnitPrice:%v,stringTotalPrice:%v\r\n", stringWeight, stringUnitPrice, stringTotalPrice) m_ComDeviceData.Weight = stringWeight m_ComDeviceData.UnitPrice = stringUnitPrice m_ComDeviceData.TotalPrice = stringTotalPrice m_WebSocketData.Command = "onCOMData" m_WebSocketData.Data = m_ComDeviceData call(m_OneDevice, "onCOMData", m_WebSocketData) copy(buf, buf[nn:nPos]) nPos = nPos - nn goto JX } } else { ss = string(buf[0:nPos]) nn = strings.IndexAny(ss, "\r\n") if nn == -1 { nPos = 0 } else { copy(buf, buf[nn:nPos]) nPos = nPos - nn goto JX } } } } else { if bGlobalVisual { s.Close() fmt.Println("关闭退出") return } } time.Sleep(300000000) } } } } func MyTCPCallBack(m_OneDevice NETDevice, com int, data string) bool { fmt.Printf("TCP指令:%v\r\n", com) println("TCP数据:", data) return true } func MyTCP(call func(m_OneDevice NETDevice, com int, data string) bool, m_OneDevice NETDevice) { // m_OneDevice.DeviceWorkPtr = []OneDeviceWork{} call(m_OneDevice, 1, "123") conn, err := net.DialTimeout("tcp", "127.0.0.1:5000", time.Second*10) if err != nil { return //panic(err) } //conn.SetDeadline() m_OneDevice.LinkOBJ = conn fmt.Fprintf(conn, "hello server\n") /* data, err := bufio.NewReader(conn).ReadString('\n') if err != nil { panic(err) } fmt.Printf("输出获得数据:%#v\n", data) */ reader := bufio.NewReader(conn) b := make([]byte, 1024*4) for { n, err := reader.Read(b) if err != nil { m_OneDevice.LinkOBJ = nil break } else { fmt.Printf("数据长度:%v", n) println("netstring:", string(b[0:n])) } } fmt.Printf("与服务器断开连接\n") } type MyData struct { iSize int data [500]byte } func IntPtr(n int) uintptr { return uintptr(n) } /* func StrPtr(s string) uintptr { return uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(s))) } */ func byteString(p []byte) string { for i := 0; i < len(p); i++ { if p[i] == 0 { return string(p[0:i]) } } return string(p) } func GetMyIPHead() string { addrs, err := net.InterfaceAddrs() if err != nil { fmt.Println(err) os.Exit(1) } var sIP string for _, address := range addrs { // 检查ip地址判断是否回环地址 if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { //fmt.Println(ipnet.IP.String()) sIP = ipnet.IP.String() break } } } nPos := strings.LastIndex(sIP, ".") var sHeadIP = Substr(sIP, 0, nPos) return sHeadIP } func searchTPCDevic() { var sIPHead = GetMyIPHead() var nCnt int = 1 var nn int = 255 / nCnt m_GlobalWG.Add(nn) for i := 0; i < nn; i++ { go FindManyTCPDevice(sIPHead, i*nCnt, nCnt) } m_GlobalWG.Wait() fmt.Println("TCP设备扫描完毕:", sGlobalTCPIPArray) } func FindManyTCPDevice(sHeadIP string, nB int, nCnt int) ([]string, []int, []string) { var sDeviceTypeArray []string = []string{} var nPortArray []int = []int{} var sIPArray []string = []string{} /* addrs, err := net.InterfaceAddrs() if err != nil { fmt.Println(err) os.Exit(1) } var sIP string for _, address := range addrs { // 检查ip地址判断是否回环地址 if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { //fmt.Println(ipnet.IP.String()) sIP = ipnet.IP.String() break } } } nPos := strings.LastIndex(sIP, ".") var sHeadIP = Substr(sIP, 0, nPos) */ var i int var sIP string for i = nB; i < nB+nCnt; i++ { sIP = sHeadIP + "." + strconv.Itoa(i) conn, err := net.DialTimeout("tcp", sIP+":4001", time.Second*1) if err != nil { //fmt.Println("连接" + sIP + "失败") } else { fmt.Println("连接上了:" + sIP) conn.Close() m_LinkRW.Lock() //return "ATCP", 4001, sIP //sDeviceTypeArray = append(sDeviceTypeArray, "ATCP") //nPortArray = append(nPortArray, 4001) //sIPArray = append(sIPArray, sIP) sGlobalTCPDeviceTypeArray = append(sGlobalTCPDeviceTypeArray, "ATCP") nGlobalTCPPortArray = append(nGlobalTCPPortArray, 4001) sGlobalTCPIPArray = append(sGlobalTCPIPArray, sIP) m_LinkRW.Unlock() } } m_GlobalWG.Done() return sDeviceTypeArray, nPortArray, sIPArray } func FindTCPDevice() (string, int, string) { if bGlobalVisual { return "TM-15H", 4001, "192.168.0.150" } addrs, err := net.InterfaceAddrs() if err != nil { fmt.Println(err) os.Exit(1) } var sIP string for _, address := range addrs { // 检查ip地址判断是否回环地址 if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { //fmt.Println(ipnet.IP.String()) sIP = ipnet.IP.String() break } } } nPos := strings.LastIndex(sIP, ".") var sHeadIP = Substr(sIP, 0, nPos) var i int for i = 1; i < 256; i++ { if bGlobalVisual { return "TM-15H", 4001, "192.168.0.150" } sIP = sHeadIP + "." + strconv.Itoa(i) + ":4001" conn, err := net.DialTimeout("tcp", sIP, time.Second*1) if err != nil { fmt.Println("连接" + sIP + "失败") } else { fmt.Println("连接上了:" + sIP) conn.Close() return "TM-15H", 4001, sIP } } return "", 0, "" } func InitDevice(bInitDevice bool) { if bInitDevice { m_DeviceMap = make(map[string]NETDevice) m_DeviceTypeEventMap = make(map[string]DeviceEventST) var m_COMDeviceEvent DeviceEventST m_COMDeviceEvent.DeviceType = "ACS-15Ab" //m_COMDeviceEvent.EventArray = []oneEvent{oneEvent{"onCOMData", "串口实时重量信息"}, oneEvent{"onCOMEvent", "串口触发事件"}} m_COMDeviceEvent.EventArray = []oneEvent{oneEvent{"onCOMData", "串口实时重量信息"}} m_DeviceTypeEventMap["ACS-15Ab"] = m_COMDeviceEvent var m_TCPDeviceEvent DeviceEventST m_TCPDeviceEvent.DeviceType = "TM-15H" m_TCPDeviceEvent.EventArray = []oneEvent{oneEvent{"onTCPData", "TCP接收数据"}} m_DeviceTypeEventMap["TM-15H"] = m_TCPDeviceEvent } sDeviceType, sGlobalCOM = FindCOMDevice() if sGlobalCOM != "" { fmt.Println("找到的COM口为", sGlobalCOM) var m_DeviceUuid string = sDeviceType + "-" + sGlobalCOM m_DeviceRW.Lock() _, ok := m_DeviceMap[m_DeviceUuid] if !ok { var m_OneDevice NETDevice m_OneDevice.DeviceCommType = "COM" m_OneDevice.DeviceType = sDeviceType m_OneDevice.DeviceUuid = m_DeviceUuid m_OneDevice.m_EventMAP = make(map[string]WebSocketEventLink) var m_COMDeviceInfo COMDeviceInfo m_COMDeviceInfo.COMString = sGlobalCOM m_OneDevice.DeviceInfo = m_COMDeviceInfo m_OneDevice.DeviceEvent = m_DeviceTypeEventMap[sDeviceType] m_DeviceMap[m_OneDevice.DeviceUuid] = m_OneDevice go MyCOM(MyCOMReturnEvent, m_OneDevice) } m_DeviceRW.Unlock() } var nPort int var sIP string for i := 0; i < len(sGlobalTCPDeviceTypeArray); i++ { //sDeviceType, nPort, sIP = FindTCPDevice() sDeviceType = sGlobalTCPDeviceTypeArray[i] nPort = nGlobalTCPPortArray[i] sIP = sGlobalTCPIPArray[i] if sDeviceType != "" { fmt.Println("找到的TCP设备", sIP) var m_DeviceUuid string = sDeviceType + "-" + sIP m_DeviceRW.Lock() _, ok := m_DeviceMap[m_DeviceUuid] if !ok { var m_OneTCPDevice NETDevice m_OneTCPDevice.DeviceCommType = "TCP" m_OneTCPDevice.DeviceType = sDeviceType //"ATCP" m_OneTCPDevice.DeviceUuid = sDeviceType + ":" + sIP // "ATCP:" + sIP m_OneTCPDevice.m_EventMAP = make(map[string]WebSocketEventLink) var m_TCPDeviceInfo TCPDeviceInfo m_TCPDeviceInfo.IP = sIP m_TCPDeviceInfo.nPort = nPort m_OneTCPDevice.DeviceInfo = m_TCPDeviceInfo m_OneTCPDevice.DeviceEvent = m_DeviceTypeEventMap[sDeviceType] //"ATCP"] m_DeviceMap[m_OneTCPDevice.DeviceUuid] = m_OneTCPDevice fmt.Println("TCPUUID:", m_OneTCPDevice.DeviceUuid) fmt.Println("OneTCP:", m_OneTCPDevice) //go MyTCP(MyTCPCallBack, m_OneTCPDevice) } m_DeviceRW.Unlock() } } } func DeviceMap2DeviceArray() { m_NETDeviceArray = []NETDevice{} for _, m_OneDevice := range m_DeviceMap { //fmt.Println("ToArray OneDevice :%v", m_OneDevice) m_NETDeviceArray = append(m_NETDeviceArray, m_OneDevice) } //fmt.Println("m_NETDeviceArray :%v", m_NETDeviceArray) } func String(b []byte) (s string) { pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) pstring.Data = pbytes.Data pstring.Len = pbytes.Len return } func Slice(s string) (b []byte) { pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) pbytes.Data = pstring.Data pbytes.Len = pstring.Len pbytes.Cap = pstring.Len return } func QWCodeToUTF8(str string) string { var returnString string = "" var m_Bytes []byte = []byte{} nL := len(str) for i := 0; i < nL; i += 4 { sQCode := Substr(str, i, 2) sWCode := Substr(str, i+2, 2) nQCode, _ := strconv.Atoi(sQCode) nWCode, _ := strconv.Atoi(sWCode) if nQCode == 3 { nQCode = 0 nWCode += 32 m_Bytes = append(m_Bytes, (byte)(nWCode)) m_Bytes = append(m_Bytes, (byte)(nQCode)) } else { nQCode += 160 nWCode += 160 m_Bytes = append(m_Bytes, (byte)(nQCode)) m_Bytes = append(m_Bytes, (byte)(nWCode)) } } fmt.Println("区位码bytes:", m_Bytes) I := bytes.NewReader(m_Bytes) O := transform.NewReader(I, simplifiedchinese.GBK.NewDecoder()) d, e := ioutil.ReadAll(O) if e != nil { return "" } returnString = string(d[0:]) returnString = strings.Replace(returnString, "\u0000", "", -1) return returnString } func UTF8ToQWCode(str string) string { var returnString = "" buf := new(bytes.Buffer) w := transform.NewWriter(buf, simplifiedchinese.GBK.NewEncoder()) w.Write([]byte(str)) w.Close() var m_Bytes []byte = buf.Bytes() fmt.Println("GB:", m_Bytes) fmt.Println("GBLength:", len(m_Bytes)) //ASCI-32 其他 -36 var i int = 0 for i = 0; i < len(m_Bytes); { if m_Bytes[i] > 160 { returnString += fmt.Sprintf("%02d", m_Bytes[i]-160) returnString += fmt.Sprintf("%02d", m_Bytes[i+1]-160) i += 2 } else { returnString += "03" returnString += fmt.Sprintf("%02d", m_Bytes[i]-32) i += 1 } } fmt.Println("QWCode:", returnString) return returnString } func main() { /* var tt int64 tt = time.Now().Unix() time.Sleep(3000000000) fmt.Println("相差秒:", time.Now().Unix()-tt) */ //TestFS() //fmt.Println("nowtime:", mylib.GetNowTimeString()) //fmt.Println("byte[]:", []byte("成都")) //fmt.Println("区位码转串", QWCodeToUTF8("19412228")) //fmt.Println("当前时间:", mylib.GetNowTimeString()) //UTF8ToQWCode("NO1进口水果") searchTPCDevic() /* var strCOMArray []string var MyString string = "中华abc" byteArray := Slice(MyString) fmt.Println("字符串byte[]:", byteArray) strCOMArray = append(strCOMArray, "你好") strCOMArray = append(strCOMArray, "我们") strCOMArray = append(strCOMArray, "大家", "你的") delete(strCOMArray, 0) fmt.Println("字符串:", strCOMArray[3]) mylib.Hello() mylib.Hello2() */ InitDevice(true) DeviceMap2DeviceArray() //json转换开始 var m_ComDeviceData ComDeviceData var m_WebSocketData WebSocketData m_ComDeviceData.Weight = "10" m_ComDeviceData.UnitPrice = "10" m_ComDeviceData.TotalPrice = "10" m_WebSocketData.Command = "COM" m_WebSocketData.Data = m_ComDeviceData /* u, _ := m_WebSocketData.Data.(ComDeviceData) fmt.Println("强制转换后的weight:", u.TotalPrice) */ /* st := &m_WebSocketData b, err := json.Marshal(st) stb := &WebSocketData{} err = json.Unmarshal(b, &stb) fmt.Println("weight:", stb.Command, string(b)) */ //return //json转换结束 m_LinkUserMap = make(map[*websocket.Conn]OneWebSocket) //go MyCOM(MyCOMReturn) //go MyTCP(MyTCPCallBack) //调用动态库 /* var m_Data MyData dll32 := syscall.NewLazyDLL("GoDll.dll") println("call dll:", dll32.Name) InitDevice := dll32.NewProc("InitDevice") ret, _, _ := InitDevice.Call() println("get the result:", ret) GetString := dll32.NewProc("GetString") GetString.Call(uintptr(unsafe.Pointer(&m_Data))) println("iSize:", m_Data.iSize) ss := string(m_Data.data[0:]) d := mahonia.NewDecoder("gbk") str := d.ConvertString(ss) println("string:", str) */ // 先把css和脚本服务上去 http.Handle(CSS_CLIENT_PATH, http.FileServer(http.Dir(CSS_SVR_PATH))) http.Handle(DART_CLIENT_PATH, http.FileServer(http.Dir(DART_SVR_PATH))) http.Handle(CSS2_CLIENT_PATH, http.FileServer(http.Dir(CSS2_SVR_PATH))) // 网址与处理逻辑对应起来 http.HandleFunc("/", HomePage) http.Handle("/ws", websocket.Handler(OnWebSocket)) // 开始服务 fmt.Println("服务启动端口:", HTTP_PORT) err := http.ListenAndServe(":"+HTTP_PORT, nil) if err != nil { fmt.Println("服务失败 /// ", err) } else { fmt.Println("服务已经启动端口:", HTTP_PORT) } } func WriteTemplateToHttpResponse(res http.ResponseWriter, t *template.Template) error { if t == nil || res == nil { return errors.New("WriteTemplateToHttpResponse: t must not be nil.") } var buf bytes.Buffer err := t.Execute(&buf, nil) if err != nil { return err } res.Header().Set("Content-Type", "text/html; charset=utf-8") _, err = res.Write(buf.Bytes()) return err } func HomePage(res http.ResponseWriter, req *http.Request) { t, err := template.ParseFiles("web/main.html") if err != nil { fmt.Println(err) return } err = WriteTemplateToHttpResponse(res, t) if err != nil { fmt.Println(err) return } } func ActionBindEvent(ws *websocket.Conn, m_OneWebSocket OneWebSocket, data WebSocketData) bool { var m_EventInterface map[string]interface{} = data.Data.(map[string]interface{}) var EventName string m_IEventName, bOK1 := m_EventInterface["EventName"] if !bOK1 { return false } EventName = m_IEventName.(string) var m_OneNETDevice NETDevice var bOK bool m_OneNETDevice, bOK = m_DeviceMap[data.DeviceUuid] if bOK { _, ok := m_OneNETDevice.m_EventMAP[EventName] if ok { //绑定事件处理 m_OneWebSocket.m_RW.Lock() m_OneNETDevice.m_EventMAP[EventName].EventLinkArray[ws] = m_OneWebSocket m_OneWebSocket.m_RW.Unlock() return true } else { //绑定事件处理 var m_WebSocketEventLink WebSocketEventLink m_OneWebSocket.m_RW.Lock() m_WebSocketEventLink.EventLinkArray = make(map[*websocket.Conn]OneWebSocket) m_WebSocketEventLink.EventLinkArray[ws] = m_OneWebSocket m_OneNETDevice.m_EventMAP[EventName] = m_WebSocketEventLink m_OneWebSocket.m_RW.Unlock() fmt.Println("绑定事件后", m_OneNETDevice.m_EventMAP) return true } } else { return false } } func ActionUnBindEvent(ws *websocket.Conn, m_OneWebSocket OneWebSocket, data WebSocketData) bool { var m_EventInterface map[string]interface{} = data.Data.(map[string]interface{}) var EventName string m_IEventName, bOK1 := m_EventInterface["EventName"] if !bOK1 { return false } EventName = m_IEventName.(string) var m_OneNETDevice NETDevice var bOK bool m_OneNETDevice, bOK = m_DeviceMap[data.DeviceUuid] if bOK { _, ok := m_OneNETDevice.m_EventMAP[EventName] if ok { m_OneWebSocket.m_RW.Lock() delete(m_OneNETDevice.m_EventMAP[EventName].EventLinkArray, ws) m_OneWebSocket.m_RW.Unlock() } return true } else { return false } } func GZDataString(str string, nL int) string { var iL = len(str) if nL <= iL { str = Substr(str, 0, nL) } else { for i := 0; i < nL-iL; i++ { str = "0" + str } } return str } func SendDeviceCommand(ws *websocket.Conn, m_OneDevice NETDevice, Command string, sendString string) { if m_OneDevice.DeviceCommType == "COM" { } else if m_OneDevice.DeviceCommType == "TCP" { var m_TCPDeviceInfo TCPDeviceInfo = m_OneDevice.DeviceInfo.(TCPDeviceInfo) conn, err := net.DialTimeout("tcp", m_TCPDeviceInfo.IP+":4001", time.Second*10) if err != nil { fmt.Println("连接失败:", m_TCPDeviceInfo.IP+":4001") return //panic(err) } defer conn.Close() if err := conn.SetReadDeadline(time.Now().Add(time.Second * 4)); err != nil { return } m_sendbytes := []byte(sendString) fmt.Println("sendCommand", sendString) conn.Write(m_sendbytes) fmt.Println("开始读取") var returnString string reader := bufio.NewReader(conn) b := make([]byte, 1024*4) //for { n, err := reader.Read(b) if err != nil { m_OneDevice.LinkOBJ = nil //break } else { fmt.Printf("数据长度:%v", n) returnString = string(b[0:n]) println("netstring:", returnString) } var m_WebSocketData WebSocketData m_WebSocketData.Command = Command m_WebSocketData.DeviceType = m_OneDevice.DeviceType m_WebSocketData.DeviceUuid = m_OneDevice.DeviceUuid var m_ReturnMessage ReturnMessage m_ReturnMessage.OK = false m_ReturnMessage.Msg = "未知错误" switch Command { case "CLEARPLU": if strings.Index(returnString, "0iaa0") != -1 { m_ReturnMessage.OK = true m_ReturnMessage.Msg = "清除PLU成功" } else { m_ReturnMessage.OK = false m_ReturnMessage.Msg = "清除PLU失败" } case "SETPLU": if strings.Index(returnString, "0v0001a0") != -1 { m_ReturnMessage.OK = true m_ReturnMessage.Msg = "设置PLU成功" } else { m_ReturnMessage.OK = false m_ReturnMessage.Msg = "设置PLU失败" } case "READPLU": //读取PLU if strings.Index(returnString, "0u") != -1 && strings.Index(returnString, "E\r\n") != -1 { m_ReturnMessage.OK = true m_ReturnMessage.Msg = "读取PLU成功" var m_OnePLU OnePLU m_OnePLU.PLUNum = Substr(returnString, 2, 4) m_OnePLU.GoodNum = Substr(returnString, 7, 7) m_OnePLU.Price = Substr(returnString, 14, 6) m_OnePLU.GoodType = Substr(returnString, 20, 1) if m_OnePLU.GoodType == "0" { m_OnePLU.GoodType = "称重" } else if m_OnePLU.GoodType == "1" { m_OnePLU.GoodType = "计件" } else if m_OnePLU.GoodType == "2" { m_OnePLU.GoodType = "定重" } m_OnePLU.Weight = Substr(returnString, 21+2+2+2+3+2+2+13, 5) m_OnePLU.ShopNo = Substr(returnString, 21+2+2+2+3, 2) //m_OnePLU.GoodName=Substr(returnString,21+2+2+2+3+2+2+13+5, ) nB := strings.LastIndex(returnString, "B") nE := strings.LastIndex(returnString, "C") m_OnePLU.GoodName = Substr(returnString, nB+1, nE-nB-1) m_OnePLU.GoodName = QWCodeToUTF8(m_OnePLU.GoodName) m_ReturnMessage.MsgData = m_OnePLU } else { m_ReturnMessage.OK = false m_ReturnMessage.Msg = "读取PLU信息失败" } case "BACKREPORT": //回收报表 if strings.Index(returnString, "0j") != -1 && strings.Index(returnString, "bc\r\n") != -1 { m_ReturnMessage.OK = true m_ReturnMessage.Msg = "回收报表成功" ss := Substr(returnString, 6, 2) if ss == "ac" { m_ReturnMessage.Msg = "无记录可回收" } else { var m_ReportOneRecord ReportOneRecord m_ReportOneRecord.RecordNum = Substr(returnString, 2, 4) m_ReportOneRecord.RecordTime = Substr(returnString, 2+4+1, 10) var sTime string = "" sTime = "20" + Substr(m_ReportOneRecord.RecordTime, 0, 2) + "年" + Substr(m_ReportOneRecord.RecordTime, 2, 2) + "月" + Substr(m_ReportOneRecord.RecordTime, 4, 2) + "日 " + Substr(m_ReportOneRecord.RecordTime, 6, 2) + "时" + Substr(m_ReportOneRecord.RecordTime, 8, 2) + "分" m_ReportOneRecord.RecordTime = sTime m_ReportOneRecord.DeptNo = Substr(returnString, 2+4+1+10, 2) m_ReportOneRecord.ShopNo = Substr(returnString, 2+4+1+12, 2) m_ReportOneRecord.PLUNum = Substr(returnString, 2+4+1+12+2, 4) m_ReportOneRecord.Weight = Substr(returnString, 2+4+1+12+2+4, 6) d, _ := strconv.Atoi(m_ReportOneRecord.Weight) var fWeight float32 = float32(float32(d) / 10000.0) m_ReportOneRecord.Weight = fmt.Sprint(fWeight, "kg") m_ReportOneRecord.Price = Substr(returnString, 2+4+1+12+2+4+6, 6) d, _ = strconv.Atoi(m_ReportOneRecord.Price) var fPrice float32 = float32(float32(d) / 1000.0) m_ReportOneRecord.Price = fmt.Sprint(fPrice, "元/kg") m_ReportOneRecord.Total = Substr(returnString, 2+4+1+12+2+4+6+6, 7) d, _ = strconv.Atoi(m_ReportOneRecord.Total) var fTotal float32 = float32(float32(d) / 1000.0) m_ReportOneRecord.Total = fmt.Sprint(fTotal, "元") m_ReportOneRecord.DiscountTotal = Substr(returnString, 2+4+1+12+2+4+6+6+7, 7) d, _ = strconv.Atoi(m_ReportOneRecord.DiscountTotal) var fDiscountTotal float32 = float32(float32(d) / 1000.0) m_ReportOneRecord.DiscountTotal = fmt.Sprint(fDiscountTotal, "元") m_ReportOneRecord.BalanceNum = Substr(returnString, 2+4+1+12+2+4+6+6+7+7+10, 2) m_ReturnMessage.MsgData = m_ReportOneRecord } } else { if strings.Index(returnString, "ac") != -1 { m_ReturnMessage.Msg = "无记录可回收" m_ReturnMessage.OK = true } else { m_ReturnMessage.OK = false m_ReturnMessage.Msg = "回收报表失败" } } case "CLAERREPORT": //清除报表 if strings.Index(returnString, "0ha\r\n") != -1 { m_ReturnMessage.OK = true m_ReturnMessage.Msg = "清除报表成功" } else { m_ReturnMessage.OK = false m_ReturnMessage.Msg = "清除报表失败" } case "SETTIME": //校时 if strings.Index(returnString, "0p\r\n") != 1 { m_ReturnMessage.OK = true m_ReturnMessage.Msg = "设置时间成功" } else { m_ReturnMessage.OK = false m_ReturnMessage.Msg = "设置时间失败" } } m_WebSocketData.Data = m_ReturnMessage if err = websocket.JSON.Send(ws, m_WebSocketData); err != nil { } else { bb, err1 := json.Marshal(m_WebSocketData) str := string(bb) if err1 == nil { fmt.Println("向客户端发送:", str) } } //} fmt.Printf("与服务器断开连接\n") //conn.Close() if err := conn.SetReadDeadline(time.Time{}); err != nil { } } } func OnWebSocket(ws *websocket.Conn) { defer ws.Close() var data WebSocketData var err error var str string ss := ws.LocalAddr().String() fmt.Println("连接上来WebSocket", ss) if strings.Index(ss, "ws://localhost") == -1 && strings.Index(ss, "ws://127.0.0.1") == -1 { data.Command = "KILL" if err = websocket.JSON.Send(ws, data); err != nil { } ws.Close() return } m_LinkRW.Lock() var m_OneWebSocket OneWebSocket m_LinkUserMap[ws] = m_OneWebSocket data.Command = "LISTDEVICE" data.Data = m_NETDeviceArray bArray, _ := json.Marshal(data) fmt.Println("m_NETDeviceArray :%v", string(bArray)) if err = websocket.JSON.Send(ws, data); err != nil { } else { bb, err1 := json.Marshal(data) str = string(bb) if err1 == nil { fmt.Println("向客户端发送:", str) } } m_LinkRW.Unlock() for { /* if err = websocket.Message.Receive(ws, &str); err != nil { break } else { fmt.Println("从客户端收到:", str) } str = "hello, I'm server." if err = websocket.Message.Send(ws, str); err != nil { break } else { fmt.Println("向客户端发送:", str) } */ data.Command = "" data.Data = nil if err = websocket.JSON.Receive(ws, &data); err != nil { break } else { if data.Command != "" { fmt.Println("从客户端收到命令:", data.Command) } if data.Data != nil { fmt.Println("从客户端收到数据:", data.Data) } switch data.Command { case "HEART": if err = websocket.JSON.Send(ws, data); err != nil { break } case "BINDEVENT": if ActionBindEvent(ws, m_OneWebSocket, data) { data.Data = "true" if err = websocket.JSON.Send(ws, data); err != nil { break } } case "UNBINDEVENT": if ActionUnBindEvent(ws, m_OneWebSocket, data) { data.Data = "true" if err = websocket.JSON.Send(ws, data); err != nil { break } } case "SEARCHDEVICE": m_SearchRW.Lock() bGlobalSearchDevice = true m_LinkRW.Lock() // 遍历map for k, _ := range m_DeviceMap { delete(m_DeviceMap, k) } m_LinkRW.Unlock() time.Sleep(2000000000) fmt.Println("发送:LISTDEVICE") bGlobalSearchDevice = false searchTPCDevic() InitDevice(false) m_LinkRW.Lock() DeviceMap2DeviceArray() data.Command = "LISTDEVICE" data.Data = m_NETDeviceArray if err = websocket.JSON.Send(ws, data); err != nil { m_LinkRW.Unlock() m_SearchRW.Unlock() break } else { } m_LinkRW.Unlock() m_SearchRW.Unlock() case "SETVISUAL": m_LinkRW.Lock() // 遍历map for k, _ := range m_DeviceMap { delete(m_DeviceMap, k) } m_LinkRW.Unlock() fmt.Println("清除原来设备完毕", m_DeviceMap) bGlobalVisual = true InitDevice(false) m_LinkRW.Lock() DeviceMap2DeviceArray() data.Command = "LISTDEVICE" data.Data = m_NETDeviceArray if err = websocket.JSON.Send(ws, data); err != nil { m_LinkRW.Unlock() break } else { } m_LinkRW.Unlock() fmt.Println("DeviceMap:", m_DeviceMap) case "NOVISUAL": fmt.Println("清除原来设备") m_LinkRW.Lock() // 遍历map for k, _ := range m_DeviceMap { delete(m_DeviceMap, k) } m_LinkRW.Unlock() fmt.Println("清除原来设备完毕", m_DeviceMap) bGlobalVisual = false InitDevice(false) fmt.Println("发送设备") m_LinkRW.Lock() DeviceMap2DeviceArray() data.Command = "LISTDEVICE" data.Data = m_NETDeviceArray fmt.Println("发送设备...") if err = websocket.JSON.Send(ws, data); err != nil { m_LinkRW.Unlock() break } else { } m_LinkRW.Unlock() case "SETPLU": fmt.Println("设置PLU", data) m_LinkRW.Lock() m_OneDevice, _ok := m_DeviceMap[data.DeviceUuid] m_OneDevice.LinkOBJ = 1 if bGlobalVisual { m_OneDevice.LinkOBJ = 1 } if _ok && m_OneDevice.LinkOBJ != nil { var stringByte string = "!0V" var m_DataInterface map[string]interface{} = data.Data.(map[string]interface{}) var TStr string sPLUNum, bOK1 := m_DataInterface["sPLUNum"] if !bOK1 { } else { TStr = sPLUNum.(string) TStr = GZDataString(TStr, 4) stringByte += TStr stringByte += "A" sGoodNum, bOK1 := m_DataInterface["sGoodNum"] if !bOK1 { } else { TStr = sGoodNum.(string) TStr = GZDataString(TStr, 7) stringByte += TStr sPrice, bOK1 := m_DataInterface["sPrice"] if !bOK1 { } else { TStr = sPrice.(string) TStr = GZDataString(TStr, 6) stringByte += TStr sGoodType, bOK1 := m_DataInterface["sGoodType"] if !bOK1 { } else { TStr = sGoodType.(string) if TStr == "WEIGHT" { stringByte += "0" } else if TStr == "COUNT" { stringByte += "1" } else if TStr == "DOTWEIGHT" { stringByte += "3" } stringByte += "00" //特殊信息1 stringByte += "00" //特殊信息2 stringByte += "00" //特殊信息3 stringByte += "000" //有效期 sShopNo, bOK1 := m_DataInterface["sShopNo"] if !bOK1 { } else { TStr = sShopNo.(string) TStr = GZDataString(TStr, 2) stringByte += TStr stringByte += "00" //部门 stringByte += "0000000000000" //为13位数字代号 sWeight, bOK1 := m_DataInterface["sWeight"] if !bOK1 { } else { TStr = sWeight.(string) TStr = GZDataString(TStr, 5) stringByte += TStr //皮重 stringByte += "00" //标签号 stringByte += "00" //是否打折 stringByte += "00" //第一时间段 stringByte += "00" stringByte += "00" stringByte += "00" //第二时间段 stringByte += "00" stringByte += "00" stringByte += "00" //第三时间段 stringByte += "00" stringByte += "00" stringByte += "00" //第四时间段 stringByte += "00" stringByte += "00" stringByte += "B" //为分隔符 sGoodName, bOK1 := m_DataInterface["sGoodName"] if !bOK1 { } else { TStr = sGoodName.(string) stringByte += UTF8ToQWCode(TStr) stringByte += "CDE\r\n" fmt.Println("开始发送:", stringByte) m_LinkRW.Unlock() SendDeviceCommand(ws, m_OneDevice, "SETPLU", stringByte) m_LinkRW.Lock() /* var m_OneDeviceWork OneDeviceWork m_OneDeviceWork.Command = "SETPLU" m_OneDeviceWork.SendString = stringByte fmt.Println("SendString:", m_OneDeviceWork.SendString) m_OneDeviceWork.conn = ws m_OneDevice.DeviceWorkPtr = append(m_OneDevice.DeviceWorkPtr, m_OneDeviceWork) */ } } } } } } } //var m_TCP net.Conn = oneDevice.LinkOBJ.(net.Conn) //m_TCP.Write([]byte(stringByte)) } else { fmt.Println("所有设备:", m_DeviceMap) fmt.Println("未找到设备:", data.DeviceUuid) } m_LinkRW.Unlock() case "READPLU": fmt.Println("读取PLU", data) m_LinkRW.Lock() m_OneDevice, _ok := m_DeviceMap[data.DeviceUuid] m_OneDevice.LinkOBJ = 1 if bGlobalVisual { m_OneDevice.LinkOBJ = 1 } if _ok && m_OneDevice.LinkOBJ != nil { var m_DataInterface map[string]interface{} = data.Data.(map[string]interface{}) var TStr string = "1" sPLUNum, bOK1 := m_DataInterface["sPLUNum"] if !bOK1 { } else { TStr = sPLUNum.(string) } var readPLUString string = mylib.GetReadPLUString(TStr) m_LinkRW.Unlock() SendDeviceCommand(ws, m_OneDevice, "READPLU", readPLUString) } else { m_LinkRW.Unlock() } case "CLEARPLU": fmt.Println("清空PLU", data) m_LinkRW.Lock() m_OneDevice, _ok := m_DeviceMap[data.DeviceUuid] m_OneDevice.LinkOBJ = 1 if bGlobalVisual { m_OneDevice.LinkOBJ = 1 } if _ok && m_OneDevice.LinkOBJ != nil { var ClearPLUString string = mylib.GetClearPLUString() m_LinkRW.Unlock() SendDeviceCommand(ws, m_OneDevice, "CLEARPLU", ClearPLUString) } else { m_LinkRW.Unlock() } case "BACKREPORT": fmt.Println("回收报表", data) m_LinkRW.Lock() m_OneDevice, _ok := m_DeviceMap[data.DeviceUuid] m_OneDevice.LinkOBJ = 1 if bGlobalVisual { m_OneDevice.LinkOBJ = 1 } if _ok && m_OneDevice.LinkOBJ != nil { var m_DataInterface map[string]interface{} = data.Data.(map[string]interface{}) var TStr string = "1" sReportNO, bOK1 := m_DataInterface["sReportNO"] if !bOK1 { } else { TStr = sReportNO.(string) } var BackReportString string = mylib.GetBackReportString(TStr) m_LinkRW.Unlock() SendDeviceCommand(ws, m_OneDevice, "BACKREPORT", BackReportString) } else { m_LinkRW.Unlock() } case "CLEARREPORT": fmt.Println("清除报表", data) m_LinkRW.Lock() m_OneDevice, _ok := m_DeviceMap[data.DeviceUuid] m_OneDevice.LinkOBJ = 1 if bGlobalVisual { m_OneDevice.LinkOBJ = 1 } if _ok && m_OneDevice.LinkOBJ != nil { var ClearReportString string = mylib.GetClearReportString() m_LinkRW.Unlock() SendDeviceCommand(ws, m_OneDevice, "CLEARREPORT", ClearReportString) } else { m_LinkRW.Unlock() } case "SETTIME": fmt.Println("设置时间", data) m_LinkRW.Lock() m_OneDevice, _ok := m_DeviceMap[data.DeviceUuid] m_OneDevice.LinkOBJ = 1 if bGlobalVisual { m_OneDevice.LinkOBJ = 1 } if _ok && m_OneDevice.LinkOBJ != nil { var NowTimeString string = mylib.GetNowTimeString() m_LinkRW.Unlock() SendDeviceCommand(ws, m_OneDevice, "SETTIME", NowTimeString) } else { m_LinkRW.Unlock() } default: } } /* str = "hello, I'm server.JsonString" data.Msg = str */ } fmt.Println("客户端断开连接") m_LinkRW.Lock() delete(m_LinkUserMap, ws) for _, m_TOneDevice := range m_DeviceMap { for _, m_WebSocketEventLink := range m_TOneDevice.m_EventMAP { _, bOK := m_WebSocketEventLink.EventLinkArray[ws] if bOK { delete(m_WebSocketEventLink.EventLinkArray, ws) } } } m_LinkRW.Unlock() } //测试反射 func TestFS() { hl := hello hl() fv := reflect.ValueOf(hl) fmt.Println("fv is reflect.Func ?", fv.Kind() == reflect.Func) fv.Call(nil) TestFS2() TestFS3() } func TestFS2() { fv := reflect.ValueOf(prints) params := make([]reflect.Value, 1) //参数 params[0] = reflect.ValueOf(20) //参数设置为20 rs := fv.Call(params) //rs作为结果接受函数的返回值 fmt.Println("result:", rs[0].Interface().(string)) //当然也可以直接是rs[0].Interface() } func hello() { fmt.Println("Hello world!") } func prints(i int) string { fmt.Println("i =", i) return strconv.Itoa(i) } type MyType struct { i int name string } func (mt *MyType) SetI(i int) { mt.i = i } func (mt *MyType) SetName(name string) { mt.name = name } func (mt *MyType) String() string { return fmt.Sprintf("%p", mt) + "--name:" + mt.name + " i:" + strconv.Itoa(mt.i) } func TestFS3() { myType := &MyType{22, "wowzai"} //fmt.Println(myType) //就是检查一下myType对象内容 //println("---------------") mtV := reflect.ValueOf(&myType).Elem() fmt.Println("Before:", mtV.MethodByName("String").Call(nil)[0]) params := make([]reflect.Value, 1) params[0] = reflect.ValueOf(18) mtV.MethodByName("SetI").Call(params) params[0] = reflect.ValueOf("reflection test") mtV.MethodByName("SetName").Call(params) fmt.Println("After:", mtV.MethodByName("String").Call(nil)[0]) } func TestFS4() { var m_TCPPack mylib.TCPPack m_TCPPack.Name = "你哈" } /* import ( "bytes" "code.google.com/p/go.text/encoding/simplifiedchinese" "code.google.com/p/go.text/transform" "io/ioutil" ) func Decode(s []byte) ([]byte, error) { //gbk汉字byte[] 转utf8 的byte[] I := bytes.NewReader(s) O := transform.NewReader(I, simplifiedchinese.GBK.NewDecoder()) d, e := ioutil.ReadAll(O) if e != nil { return nil, e } return d, nil } func Encode(s []byte) ([]byte, error) { //utf8的byte[] 转gbk的byte[] I := bytes.NewReader(s) O := transform.NewReader(I, simplifiedchinese.GBK.NewEncoder()) d, e := ioutil.ReadAll(O) if e != nil { return nil, e } return d, nil } 复制代码 */ package mylib import ( "fmt" "time" ) type TCPPack struct { Name string } func Hello() { fmt.Println("我在库里") } func (T *TCPPack) TCPFunction(a, b int) int { return a + b } func Substr(str string, start, length int) string { rs := []rune(str) rl := len(rs) end := 0 if start < 0 { start = rl - 1 + start } end = start + length if start > end { start, end = end, start } if start < 0 { start = 0 } if start > rl { start = rl } if end < 0 { end = 0 } if end > rl { end = rl } str0 := string(rs[start:end]) rs = nil return str0 } func DataString(str string, nL int) string { var iL int = len(str) if nL <= iL { str = Substr(str, 0, nL) } else { for i := 0; i < nL-iL; i++ { str = "0" + str } } return str } func GetClearPLUString() string { return "!0IA\r\n" } func GetClearReportString() string { return "!0HA\r\n" } func GetBackReportString(strNO string) string { return "!0J" + DataString(strNO, 4) + "A\r\n" } func GetReadPLUString(strPLU string) string { return "!0U" + DataString(strPLU, 4) + "A\r\n" } func GetNowTimeString() string { var tTime time.Time = time.Now() //var m_M time.Month = tTime.Month() return fmt.Sprintf("!0P%02d%02d%02d%02d%02d\r\n", tTime.Year()-2000, (int)(tTime.Month()), tTime.Day(), tTime.Hour(), tTime.Minute()) return "" }