forked from gopcua/opcua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
305 lines (253 loc) · 6.3 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package main
import (
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os/exec"
"path"
"strings"
"text/template"
"github.com/center2m/opcua/cmd/service/goname"
)
var in, out, pkg string
func main() {
log.SetFlags(0)
flag.StringVar(&in, "in", "schema/Opc.Ua.Types.bsd", "Path to Opc.Ua.Types.bsd file")
flag.StringVar(&out, "out", "ua", "Path to output directory")
flag.StringVar(&pkg, "pkg", "ua", "Go package name")
flag.Parse()
dict, err := ReadTypes(in)
if err != nil {
log.Fatalf("Failed to read type definitions: %s", err)
}
writeEnums(Enums(dict))
writeServiceRegister(ExtObjects(dict))
writeExtObjects(ExtObjects(dict))
}
func writeEnums(enums []Type) {
var b bytes.Buffer
if err := FormatTypes(&b, enums); err != nil {
log.Fatal(err)
}
write(b.Bytes(), path.Join(out, "enums_gen.go"))
}
func writeExtObjects(objs []Type) {
var b bytes.Buffer
if err := FormatTypes(&b, objs); err != nil {
log.Fatal(err)
}
write(b.Bytes(), path.Join(out, "extobjs_gen.go"))
}
func writeServiceRegister(objs []Type) {
var b bytes.Buffer
if err := tmplRegister.Execute(&b, objs); err != nil {
log.Fatal(err)
}
write(b.Bytes(), path.Join(out, "service_gen.go"))
}
func write(src []byte, filename string) {
var b bytes.Buffer
if err := tmplHeader.Execute(&b, pkg); err != nil {
log.Fatalf("Failed to generate header: %s", err)
}
b.Write(src)
if err := ioutil.WriteFile(filename, b.Bytes(), 0644); err != nil {
log.Fatalf("Failed to write %s: %v", filename, err)
}
if err := exec.Command("goimports", "-w", filename).Run(); err != nil {
fmt.Println(string(src))
log.Fatalf("Failed to format %s: %v", filename, err)
}
log.Printf("Wrote %s", filename)
}
var tmplHeader = template.Must(template.New("").Parse(`
// Copyright 2018-2019 opcua authors. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
// Code generated by cmd/service. DO NOT EDIT!
package {{.}}
import "time"
`))
func Enums(dict *TypeDictionary) []Type {
var enums []Type
for _, t := range dict.Enums {
e := Type{
Name: goname.Format(t.Name),
Kind: KindEnum,
}
switch {
case t.Bits <= 8:
e.Type = "uint8"
case t.Bits <= 16:
e.Type = "uint16"
case t.Bits <= 32:
e.Type = "uint32"
default:
e.Type = "uint64"
}
for _, val := range t.Values {
v := Value{
Name: goname.Format(e.Name + val.Name),
Value: val.Value,
}
e.Values = append(e.Values, v)
}
enums = append(enums, e)
}
return enums
}
func ExtObjects(dict *TypeDictionary) []Type {
baseTypes := map[string]*Type{
// Extensionobject is the base class for all extension objects.
"ua:ExtensionObject": &Type{Name: "ExtensionObject"},
// DataTypeDefinition is referenced in Opc.Ua.Types.bsd but not defined there
// From what I can tell it is an abstract base class without any fields.
// We define it here to be able to generate code for derived classes.
"tns:DataTypeDefinition": &Type{Name: "DataTypeDefinition"},
}
var objects []Type
for _, t := range dict.Types {
// check if the base type is derived from ExtensionObject
baseType := baseTypes[t.BaseType]
if baseType == nil {
continue
}
o := Type{
Name: goname.Format(t.Name),
Kind: KindExtensionObject,
Base: baseType,
}
for _, f := range t.Fields {
// skip fields containing the length of an array since
// we create an array type
if t.IsLengthField(f) {
continue
}
of := Field{
Name: goname.Format(f.Name),
Type: goFieldType(f),
}
if of.Name == "AttributeID" {
of.Type = "AttributeID"
}
o.Fields = append(o.Fields, of)
}
// register it as derived from ExtensionObject
// we need to register it with target namespace 'tns:' since t.Name only contains the
// base name.
baseTypes["tns:"+t.Name] = &o
objects = append(objects, o)
}
return objects
}
type Kind int
const (
KindEnum Kind = iota
KindExtensionObject
)
type Type struct {
// Name is the Go name of the OPC/UA type.
Name string
// Type is the Go type of the OPC/UA type.
Type string
// Kind is the kind of OPC/UA type.
Kind Kind
// Base is the OPC/UA type this type is derived from.
Base *Type
// Fields is the list of struct fields.
Fields []Field
// Values is the list of enum values.
Values []Value
}
type Value struct {
Name string
Value int
}
type Field struct {
Name string
Type string
}
func FormatTypes(w io.Writer, types []Type) error {
for _, t := range types {
if err := FormatType(w, t); err != nil {
return err
}
}
return nil
}
func FormatType(w io.Writer, t Type) error {
switch t.Kind {
case KindEnum:
return tmplEnum.Execute(w, t)
case KindExtensionObject:
return tmplExtObject.Execute(w, t)
default:
return fmt.Errorf("invalid type: %d", t.Kind)
}
}
var tmplEnum = template.Must(template.New("").Parse(`
type {{.Name}} {{.Type}}
const (
{{$Name := .Name}}
{{range $i, $v := .Values}}{{$v.Name}} {{$Name}} = {{$v.Value}}
{{end}}
)
`))
var tmplExtObject = template.Must(template.New("").Parse(`
{{if .Fields}}
type {{.Name}} struct {
{{range $i, $v := .Fields}}{{$v.Name}} {{$v.Type}}
{{end}}
}
{{end}}
`))
var funcs = template.FuncMap{
"isService": func(s string) bool {
return strings.HasSuffix(s, "Request") || strings.HasSuffix(s, "Response") || s == "ServiceFault"
},
}
var tmplRegister = template.Must(template.New("").Funcs(funcs).Parse(`
import "github.com/center2m/opcua/id"
func init() {
{{- range $i, $v := . -}}
{{- if isService $v.Name -}}
register(id.{{$v.Name}}_Encoding_DefaultBinary, new({{$v.Name}}))
{{end -}}
{{end -}}
}
`))
var builtins = map[string]string{
"opc:Boolean": "bool",
"opc:Byte": "uint8",
"opc:SByte": "int8",
"opc:Int16": "int16",
"opc:Int32": "int32",
"opc:Int64": "int64",
"opc:UInt16": "uint16",
"opc:UInt32": "uint32",
"opc:UInt64": "uint64",
"opc:Float": "float32",
"opc:Double": "float64",
"opc:String": "string",
"opc:DateTime": "time.Time",
"opc:ByteString": "[]byte",
"ua:StatusCode": "StatusCode",
"opc:Guid": "*GUID",
}
func goFieldType(f *StructField) string {
t, builtin := builtins[f.Type]
if t == "" {
prefix := strings.NewReplacer("ua:", "", "tns:", "")
t = goname.Format(prefix.Replace(f.Type))
}
if !f.IsEnum && !builtin {
t = "*" + t
}
if f.IsSlice() {
t = "[]" + t
}
return t
}