repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
rivo/tview
table.go
InsertRow
func (t *Table) InsertRow(row int) *Table { if row >= len(t.cells) { return t } t.cells = append(t.cells, nil) // Extend by one. copy(t.cells[row+1:], t.cells[row:]) // Shift down. t.cells[row] = nil // New row is uninitialized. return t }
go
func (t *Table) InsertRow(row int) *Table { if row >= len(t.cells) { return t } t.cells = append(t.cells, nil) // Extend by one. copy(t.cells[row+1:], t.cells[row:]) // Shift down. t.cells[row] = nil // New row is uninitialized. return t }
[ "func", "(", "t", "*", "Table", ")", "InsertRow", "(", "row", "int", ")", "*", "Table", "{", "if", "row", ">=", "len", "(", "t", ".", "cells", ")", "{", "return", "t", "\n", "}", "\n", "t", ".", "cells", "=", "append", "(", "t", ".", "cells", ",", "nil", ")", "// Extend by one.", "\n", "copy", "(", "t", ".", "cells", "[", "row", "+", "1", ":", "]", ",", "t", ".", "cells", "[", "row", ":", "]", ")", "// Shift down.", "\n", "t", ".", "cells", "[", "row", "]", "=", "nil", "// New row is uninitialized.", "\n", "return", "t", "\n", "}" ]
// InsertRow inserts a row before the row with the given index. Cells on the // given row and below will be shifted to the bottom by one row. If "row" is // equal or larger than the current number of rows, this function has no effect.
[ "InsertRow", "inserts", "a", "row", "before", "the", "row", "with", "the", "given", "index", ".", "Cells", "on", "the", "given", "row", "and", "below", "will", "be", "shifted", "to", "the", "bottom", "by", "one", "row", ".", "If", "row", "is", "equal", "or", "larger", "than", "the", "current", "number", "of", "rows", "this", "function", "has", "no", "effect", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/table.go#L481-L489
train
rivo/tview
table.go
InsertColumn
func (t *Table) InsertColumn(column int) *Table { for row := range t.cells { if column >= len(t.cells[row]) { continue } t.cells[row] = append(t.cells[row], nil) // Extend by one. copy(t.cells[row][column+1:], t.cells[row][column:]) // Shift to the right. t.cells[row][column] = &TableCell{} // New element is an uninitialized table cell. } return t }
go
func (t *Table) InsertColumn(column int) *Table { for row := range t.cells { if column >= len(t.cells[row]) { continue } t.cells[row] = append(t.cells[row], nil) // Extend by one. copy(t.cells[row][column+1:], t.cells[row][column:]) // Shift to the right. t.cells[row][column] = &TableCell{} // New element is an uninitialized table cell. } return t }
[ "func", "(", "t", "*", "Table", ")", "InsertColumn", "(", "column", "int", ")", "*", "Table", "{", "for", "row", ":=", "range", "t", ".", "cells", "{", "if", "column", ">=", "len", "(", "t", ".", "cells", "[", "row", "]", ")", "{", "continue", "\n", "}", "\n", "t", ".", "cells", "[", "row", "]", "=", "append", "(", "t", ".", "cells", "[", "row", "]", ",", "nil", ")", "// Extend by one.", "\n", "copy", "(", "t", ".", "cells", "[", "row", "]", "[", "column", "+", "1", ":", "]", ",", "t", ".", "cells", "[", "row", "]", "[", "column", ":", "]", ")", "// Shift to the right.", "\n", "t", ".", "cells", "[", "row", "]", "[", "column", "]", "=", "&", "TableCell", "{", "}", "// New element is an uninitialized table cell.", "\n", "}", "\n", "return", "t", "\n", "}" ]
// InsertColumn inserts a column before the column with the given index. Cells // in the given column and to its right will be shifted to the right by one // column. Rows that have fewer initialized cells than "column" will remain // unchanged.
[ "InsertColumn", "inserts", "a", "column", "before", "the", "column", "with", "the", "given", "index", ".", "Cells", "in", "the", "given", "column", "and", "to", "its", "right", "will", "be", "shifted", "to", "the", "right", "by", "one", "column", ".", "Rows", "that", "have", "fewer", "initialized", "cells", "than", "column", "will", "remain", "unchanged", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/table.go#L495-L505
train
rivo/tview
table.go
ScrollToBeginning
func (t *Table) ScrollToBeginning() *Table { t.trackEnd = false t.columnOffset = 0 t.rowOffset = 0 return t }
go
func (t *Table) ScrollToBeginning() *Table { t.trackEnd = false t.columnOffset = 0 t.rowOffset = 0 return t }
[ "func", "(", "t", "*", "Table", ")", "ScrollToBeginning", "(", ")", "*", "Table", "{", "t", ".", "trackEnd", "=", "false", "\n", "t", ".", "columnOffset", "=", "0", "\n", "t", ".", "rowOffset", "=", "0", "\n", "return", "t", "\n", "}" ]
// ScrollToBeginning scrolls the table to the beginning to that the top left // corner of the table is shown. Note that this position may be corrected if // there is a selection.
[ "ScrollToBeginning", "scrolls", "the", "table", "to", "the", "beginning", "to", "that", "the", "top", "left", "corner", "of", "the", "table", "is", "shown", ".", "Note", "that", "this", "position", "may", "be", "corrected", "if", "there", "is", "a", "selection", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/table.go#L523-L528
train
rivo/tview
table.go
ScrollToEnd
func (t *Table) ScrollToEnd() *Table { t.trackEnd = true t.columnOffset = 0 t.rowOffset = len(t.cells) return t }
go
func (t *Table) ScrollToEnd() *Table { t.trackEnd = true t.columnOffset = 0 t.rowOffset = len(t.cells) return t }
[ "func", "(", "t", "*", "Table", ")", "ScrollToEnd", "(", ")", "*", "Table", "{", "t", ".", "trackEnd", "=", "true", "\n", "t", ".", "columnOffset", "=", "0", "\n", "t", ".", "rowOffset", "=", "len", "(", "t", ".", "cells", ")", "\n", "return", "t", "\n", "}" ]
// ScrollToEnd scrolls the table to the beginning to that the bottom left corner // of the table is shown. Adding more rows to the table will cause it to // automatically scroll with the new data. Note that this position may be // corrected if there is a selection.
[ "ScrollToEnd", "scrolls", "the", "table", "to", "the", "beginning", "to", "that", "the", "bottom", "left", "corner", "of", "the", "table", "is", "shown", ".", "Adding", "more", "rows", "to", "the", "table", "will", "cause", "it", "to", "automatically", "scroll", "with", "the", "new", "data", ".", "Note", "that", "this", "position", "may", "be", "corrected", "if", "there", "is", "a", "selection", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/table.go#L534-L539
train
rivo/tview
demos/presentation/introduction.go
Introduction
func Introduction(nextSlide func()) (title string, content tview.Primitive) { list := tview.NewList(). AddItem("A Go package for terminal based UIs", "with a special focus on rich interactive widgets", '1', nextSlide). AddItem("Based on github.com/gdamore/tcell", "Like termbox but better (see tcell docs)", '2', nextSlide). AddItem("Designed to be simple", `"Hello world" is 5 lines of code`, '3', nextSlide). AddItem("Good for data entry", `For charts, use "termui" - for low-level views, use "gocui" - ...`, '4', nextSlide). AddItem("Extensive documentation", "Everything is documented, examples in GitHub wiki, demo code for each widget", '5', nextSlide) return "Introduction", Center(80, 10, list) }
go
func Introduction(nextSlide func()) (title string, content tview.Primitive) { list := tview.NewList(). AddItem("A Go package for terminal based UIs", "with a special focus on rich interactive widgets", '1', nextSlide). AddItem("Based on github.com/gdamore/tcell", "Like termbox but better (see tcell docs)", '2', nextSlide). AddItem("Designed to be simple", `"Hello world" is 5 lines of code`, '3', nextSlide). AddItem("Good for data entry", `For charts, use "termui" - for low-level views, use "gocui" - ...`, '4', nextSlide). AddItem("Extensive documentation", "Everything is documented, examples in GitHub wiki, demo code for each widget", '5', nextSlide) return "Introduction", Center(80, 10, list) }
[ "func", "Introduction", "(", "nextSlide", "func", "(", ")", ")", "(", "title", "string", ",", "content", "tview", ".", "Primitive", ")", "{", "list", ":=", "tview", ".", "NewList", "(", ")", ".", "AddItem", "(", "\"", "\"", ",", "\"", "\"", ",", "'1'", ",", "nextSlide", ")", ".", "AddItem", "(", "\"", "\"", ",", "\"", "\"", ",", "'2'", ",", "nextSlide", ")", ".", "AddItem", "(", "\"", "\"", ",", "`\"Hello world\" is 5 lines of code`", ",", "'3'", ",", "nextSlide", ")", ".", "AddItem", "(", "\"", "\"", ",", "`For charts, use \"termui\" - for low-level views, use \"gocui\" - ...`", ",", "'4'", ",", "nextSlide", ")", ".", "AddItem", "(", "\"", "\"", ",", "\"", "\"", ",", "'5'", ",", "nextSlide", ")", "\n", "return", "\"", "\"", ",", "Center", "(", "80", ",", "10", ",", "list", ")", "\n", "}" ]
// Introduction returns a tview.List with the highlights of the tview package.
[ "Introduction", "returns", "a", "tview", ".", "List", "with", "the", "highlights", "of", "the", "tview", "package", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/demos/presentation/introduction.go#L6-L14
train
rivo/tview
demos/presentation/flex.go
Flex
func Flex(nextSlide func()) (title string, content tview.Primitive) { modalShown := false pages := tview.NewPages() textView := tview.NewTextView(). SetDoneFunc(func(key tcell.Key) { if modalShown { nextSlide() modalShown = false } else { pages.ShowPage("modal") modalShown = true } }) textView.SetBorder(true).SetTitle("Flexible width, twice of middle column") flex := tview.NewFlex(). AddItem(textView, 0, 2, true). AddItem(tview.NewFlex(). SetDirection(tview.FlexRow). AddItem(tview.NewBox().SetBorder(true).SetTitle("Flexible width"), 0, 1, false). AddItem(tview.NewBox().SetBorder(true).SetTitle("Fixed height"), 15, 1, false). AddItem(tview.NewBox().SetBorder(true).SetTitle("Flexible height"), 0, 1, false), 0, 1, false). AddItem(tview.NewBox().SetBorder(true).SetTitle("Fixed width"), 30, 1, false) modal := tview.NewModal(). SetText("Resize the window to see the effect of the flexbox parameters"). AddButtons([]string{"Ok"}).SetDoneFunc(func(buttonIndex int, buttonLabel string) { pages.HidePage("modal") }) pages.AddPage("flex", flex, true, true). AddPage("modal", modal, false, false) return "Flex", pages }
go
func Flex(nextSlide func()) (title string, content tview.Primitive) { modalShown := false pages := tview.NewPages() textView := tview.NewTextView(). SetDoneFunc(func(key tcell.Key) { if modalShown { nextSlide() modalShown = false } else { pages.ShowPage("modal") modalShown = true } }) textView.SetBorder(true).SetTitle("Flexible width, twice of middle column") flex := tview.NewFlex(). AddItem(textView, 0, 2, true). AddItem(tview.NewFlex(). SetDirection(tview.FlexRow). AddItem(tview.NewBox().SetBorder(true).SetTitle("Flexible width"), 0, 1, false). AddItem(tview.NewBox().SetBorder(true).SetTitle("Fixed height"), 15, 1, false). AddItem(tview.NewBox().SetBorder(true).SetTitle("Flexible height"), 0, 1, false), 0, 1, false). AddItem(tview.NewBox().SetBorder(true).SetTitle("Fixed width"), 30, 1, false) modal := tview.NewModal(). SetText("Resize the window to see the effect of the flexbox parameters"). AddButtons([]string{"Ok"}).SetDoneFunc(func(buttonIndex int, buttonLabel string) { pages.HidePage("modal") }) pages.AddPage("flex", flex, true, true). AddPage("modal", modal, false, false) return "Flex", pages }
[ "func", "Flex", "(", "nextSlide", "func", "(", ")", ")", "(", "title", "string", ",", "content", "tview", ".", "Primitive", ")", "{", "modalShown", ":=", "false", "\n", "pages", ":=", "tview", ".", "NewPages", "(", ")", "\n", "textView", ":=", "tview", ".", "NewTextView", "(", ")", ".", "SetDoneFunc", "(", "func", "(", "key", "tcell", ".", "Key", ")", "{", "if", "modalShown", "{", "nextSlide", "(", ")", "\n", "modalShown", "=", "false", "\n", "}", "else", "{", "pages", ".", "ShowPage", "(", "\"", "\"", ")", "\n", "modalShown", "=", "true", "\n", "}", "\n", "}", ")", "\n", "textView", ".", "SetBorder", "(", "true", ")", ".", "SetTitle", "(", "\"", "\"", ")", "\n", "flex", ":=", "tview", ".", "NewFlex", "(", ")", ".", "AddItem", "(", "textView", ",", "0", ",", "2", ",", "true", ")", ".", "AddItem", "(", "tview", ".", "NewFlex", "(", ")", ".", "SetDirection", "(", "tview", ".", "FlexRow", ")", ".", "AddItem", "(", "tview", ".", "NewBox", "(", ")", ".", "SetBorder", "(", "true", ")", ".", "SetTitle", "(", "\"", "\"", ")", ",", "0", ",", "1", ",", "false", ")", ".", "AddItem", "(", "tview", ".", "NewBox", "(", ")", ".", "SetBorder", "(", "true", ")", ".", "SetTitle", "(", "\"", "\"", ")", ",", "15", ",", "1", ",", "false", ")", ".", "AddItem", "(", "tview", ".", "NewBox", "(", ")", ".", "SetBorder", "(", "true", ")", ".", "SetTitle", "(", "\"", "\"", ")", ",", "0", ",", "1", ",", "false", ")", ",", "0", ",", "1", ",", "false", ")", ".", "AddItem", "(", "tview", ".", "NewBox", "(", ")", ".", "SetBorder", "(", "true", ")", ".", "SetTitle", "(", "\"", "\"", ")", ",", "30", ",", "1", ",", "false", ")", "\n", "modal", ":=", "tview", ".", "NewModal", "(", ")", ".", "SetText", "(", "\"", "\"", ")", ".", "AddButtons", "(", "[", "]", "string", "{", "\"", "\"", "}", ")", ".", "SetDoneFunc", "(", "func", "(", "buttonIndex", "int", ",", "buttonLabel", "string", ")", "{", "pages", ".", "HidePage", "(", "\"", "\"", ")", "\n", "}", ")", "\n", "pages", ".", "AddPage", "(", "\"", "\"", ",", "flex", ",", "true", ",", "true", ")", ".", "AddPage", "(", "\"", "\"", ",", "modal", ",", "false", ",", "false", ")", "\n", "return", "\"", "\"", ",", "pages", "\n", "}" ]
// Flex demonstrates flexbox layout.
[ "Flex", "demonstrates", "flexbox", "layout", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/demos/presentation/flex.go#L9-L39
train
rivo/tview
demos/presentation/helloworld.go
HelloWorld
func HelloWorld(nextSlide func()) (title string, content tview.Primitive) { // We use a text view because we want to capture keyboard input. textView := tview.NewTextView().SetDoneFunc(func(key tcell.Key) { nextSlide() }) textView.SetBorder(true).SetTitle("Hello, world!") return "Hello, world", Code(textView, 30, 10, helloWorld) }
go
func HelloWorld(nextSlide func()) (title string, content tview.Primitive) { // We use a text view because we want to capture keyboard input. textView := tview.NewTextView().SetDoneFunc(func(key tcell.Key) { nextSlide() }) textView.SetBorder(true).SetTitle("Hello, world!") return "Hello, world", Code(textView, 30, 10, helloWorld) }
[ "func", "HelloWorld", "(", "nextSlide", "func", "(", ")", ")", "(", "title", "string", ",", "content", "tview", ".", "Primitive", ")", "{", "// We use a text view because we want to capture keyboard input.", "textView", ":=", "tview", ".", "NewTextView", "(", ")", ".", "SetDoneFunc", "(", "func", "(", "key", "tcell", ".", "Key", ")", "{", "nextSlide", "(", ")", "\n", "}", ")", "\n", "textView", ".", "SetBorder", "(", "true", ")", ".", "SetTitle", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", ",", "Code", "(", "textView", ",", "30", ",", "10", ",", "helloWorld", ")", "\n", "}" ]
// HelloWorld shows a simple "Hello world" example.
[ "HelloWorld", "shows", "a", "simple", "Hello", "world", "example", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/demos/presentation/helloworld.go#L24-L31
train
rivo/tview
demos/presentation/main.go
main
func main() { // The presentation slides. slides := []Slide{ Cover, Introduction, HelloWorld, InputField, Form, TextView1, TextView2, Table, TreeView, Flex, Grid, Colors, End, } // The bottom row has some info on where we are. info := tview.NewTextView(). SetDynamicColors(true). SetRegions(true). SetWrap(false) // Create the pages for all slides. currentSlide := 0 info.Highlight(strconv.Itoa(currentSlide)) pages := tview.NewPages() previousSlide := func() { currentSlide = (currentSlide - 1 + len(slides)) % len(slides) info.Highlight(strconv.Itoa(currentSlide)). ScrollToHighlight() pages.SwitchToPage(strconv.Itoa(currentSlide)) } nextSlide := func() { currentSlide = (currentSlide + 1) % len(slides) info.Highlight(strconv.Itoa(currentSlide)). ScrollToHighlight() pages.SwitchToPage(strconv.Itoa(currentSlide)) } for index, slide := range slides { title, primitive := slide(nextSlide) pages.AddPage(strconv.Itoa(index), primitive, true, index == currentSlide) fmt.Fprintf(info, `%d ["%d"][darkcyan]%s[white][""] `, index+1, index, title) } // Create the main layout. layout := tview.NewFlex(). SetDirection(tview.FlexRow). AddItem(pages, 0, 1, true). AddItem(info, 1, 1, false) // Shortcuts to navigate the slides. app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { if event.Key() == tcell.KeyCtrlN { nextSlide() } else if event.Key() == tcell.KeyCtrlP { previousSlide() } return event }) // Start the application. if err := app.SetRoot(layout, true).Run(); err != nil { panic(err) } }
go
func main() { // The presentation slides. slides := []Slide{ Cover, Introduction, HelloWorld, InputField, Form, TextView1, TextView2, Table, TreeView, Flex, Grid, Colors, End, } // The bottom row has some info on where we are. info := tview.NewTextView(). SetDynamicColors(true). SetRegions(true). SetWrap(false) // Create the pages for all slides. currentSlide := 0 info.Highlight(strconv.Itoa(currentSlide)) pages := tview.NewPages() previousSlide := func() { currentSlide = (currentSlide - 1 + len(slides)) % len(slides) info.Highlight(strconv.Itoa(currentSlide)). ScrollToHighlight() pages.SwitchToPage(strconv.Itoa(currentSlide)) } nextSlide := func() { currentSlide = (currentSlide + 1) % len(slides) info.Highlight(strconv.Itoa(currentSlide)). ScrollToHighlight() pages.SwitchToPage(strconv.Itoa(currentSlide)) } for index, slide := range slides { title, primitive := slide(nextSlide) pages.AddPage(strconv.Itoa(index), primitive, true, index == currentSlide) fmt.Fprintf(info, `%d ["%d"][darkcyan]%s[white][""] `, index+1, index, title) } // Create the main layout. layout := tview.NewFlex(). SetDirection(tview.FlexRow). AddItem(pages, 0, 1, true). AddItem(info, 1, 1, false) // Shortcuts to navigate the slides. app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { if event.Key() == tcell.KeyCtrlN { nextSlide() } else if event.Key() == tcell.KeyCtrlP { previousSlide() } return event }) // Start the application. if err := app.SetRoot(layout, true).Run(); err != nil { panic(err) } }
[ "func", "main", "(", ")", "{", "// The presentation slides.", "slides", ":=", "[", "]", "Slide", "{", "Cover", ",", "Introduction", ",", "HelloWorld", ",", "InputField", ",", "Form", ",", "TextView1", ",", "TextView2", ",", "Table", ",", "TreeView", ",", "Flex", ",", "Grid", ",", "Colors", ",", "End", ",", "}", "\n\n", "// The bottom row has some info on where we are.", "info", ":=", "tview", ".", "NewTextView", "(", ")", ".", "SetDynamicColors", "(", "true", ")", ".", "SetRegions", "(", "true", ")", ".", "SetWrap", "(", "false", ")", "\n\n", "// Create the pages for all slides.", "currentSlide", ":=", "0", "\n", "info", ".", "Highlight", "(", "strconv", ".", "Itoa", "(", "currentSlide", ")", ")", "\n", "pages", ":=", "tview", ".", "NewPages", "(", ")", "\n", "previousSlide", ":=", "func", "(", ")", "{", "currentSlide", "=", "(", "currentSlide", "-", "1", "+", "len", "(", "slides", ")", ")", "%", "len", "(", "slides", ")", "\n", "info", ".", "Highlight", "(", "strconv", ".", "Itoa", "(", "currentSlide", ")", ")", ".", "ScrollToHighlight", "(", ")", "\n", "pages", ".", "SwitchToPage", "(", "strconv", ".", "Itoa", "(", "currentSlide", ")", ")", "\n", "}", "\n", "nextSlide", ":=", "func", "(", ")", "{", "currentSlide", "=", "(", "currentSlide", "+", "1", ")", "%", "len", "(", "slides", ")", "\n", "info", ".", "Highlight", "(", "strconv", ".", "Itoa", "(", "currentSlide", ")", ")", ".", "ScrollToHighlight", "(", ")", "\n", "pages", ".", "SwitchToPage", "(", "strconv", ".", "Itoa", "(", "currentSlide", ")", ")", "\n", "}", "\n", "for", "index", ",", "slide", ":=", "range", "slides", "{", "title", ",", "primitive", ":=", "slide", "(", "nextSlide", ")", "\n", "pages", ".", "AddPage", "(", "strconv", ".", "Itoa", "(", "index", ")", ",", "primitive", ",", "true", ",", "index", "==", "currentSlide", ")", "\n", "fmt", ".", "Fprintf", "(", "info", ",", "`%d [\"%d\"][darkcyan]%s[white][\"\"] `", ",", "index", "+", "1", ",", "index", ",", "title", ")", "\n", "}", "\n\n", "// Create the main layout.", "layout", ":=", "tview", ".", "NewFlex", "(", ")", ".", "SetDirection", "(", "tview", ".", "FlexRow", ")", ".", "AddItem", "(", "pages", ",", "0", ",", "1", ",", "true", ")", ".", "AddItem", "(", "info", ",", "1", ",", "1", ",", "false", ")", "\n\n", "// Shortcuts to navigate the slides.", "app", ".", "SetInputCapture", "(", "func", "(", "event", "*", "tcell", ".", "EventKey", ")", "*", "tcell", ".", "EventKey", "{", "if", "event", ".", "Key", "(", ")", "==", "tcell", ".", "KeyCtrlN", "{", "nextSlide", "(", ")", "\n", "}", "else", "if", "event", ".", "Key", "(", ")", "==", "tcell", ".", "KeyCtrlP", "{", "previousSlide", "(", ")", "\n", "}", "\n", "return", "event", "\n", "}", ")", "\n\n", "// Start the application.", "if", "err", ":=", "app", ".", "SetRoot", "(", "layout", ",", "true", ")", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// Starting point for the presentation.
[ "Starting", "point", "for", "the", "presentation", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/demos/presentation/main.go#L32-L98
train
rivo/tview
demos/presentation/inputfield.go
InputField
func InputField(nextSlide func()) (title string, content tview.Primitive) { input := tview.NewInputField(). SetLabel("Enter a number: "). SetAcceptanceFunc(tview.InputFieldInteger).SetDoneFunc(func(key tcell.Key) { nextSlide() }) return "Input", Code(input, 30, 1, inputField) }
go
func InputField(nextSlide func()) (title string, content tview.Primitive) { input := tview.NewInputField(). SetLabel("Enter a number: "). SetAcceptanceFunc(tview.InputFieldInteger).SetDoneFunc(func(key tcell.Key) { nextSlide() }) return "Input", Code(input, 30, 1, inputField) }
[ "func", "InputField", "(", "nextSlide", "func", "(", ")", ")", "(", "title", "string", ",", "content", "tview", ".", "Primitive", ")", "{", "input", ":=", "tview", ".", "NewInputField", "(", ")", ".", "SetLabel", "(", "\"", "\"", ")", ".", "SetAcceptanceFunc", "(", "tview", ".", "InputFieldInteger", ")", ".", "SetDoneFunc", "(", "func", "(", "key", "tcell", ".", "Key", ")", "{", "nextSlide", "(", ")", "\n", "}", ")", "\n", "return", "\"", "\"", ",", "Code", "(", "input", ",", "30", ",", "1", ",", "inputField", ")", "\n", "}" ]
// InputField demonstrates the InputField.
[ "InputField", "demonstrates", "the", "InputField", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/demos/presentation/inputfield.go#L33-L40
train
rivo/tview
grid.go
SetMinSize
func (g *Grid) SetMinSize(row, column int) *Grid { if row < 0 || column < 0 { panic("Invalid minimum row/column size") } g.minHeight, g.minWidth = row, column return g }
go
func (g *Grid) SetMinSize(row, column int) *Grid { if row < 0 || column < 0 { panic("Invalid minimum row/column size") } g.minHeight, g.minWidth = row, column return g }
[ "func", "(", "g", "*", "Grid", ")", "SetMinSize", "(", "row", ",", "column", "int", ")", "*", "Grid", "{", "if", "row", "<", "0", "||", "column", "<", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "g", ".", "minHeight", ",", "g", ".", "minWidth", "=", "row", ",", "column", "\n", "return", "g", "\n", "}" ]
// SetMinSize sets an absolute minimum width for rows and an absolute minimum // height for columns. Panics if negative values are provided.
[ "SetMinSize", "sets", "an", "absolute", "minimum", "width", "for", "rows", "and", "an", "absolute", "minimum", "height", "for", "columns", ".", "Panics", "if", "negative", "values", "are", "provided", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/grid.go#L139-L145
train
rivo/tview
grid.go
SetBordersColor
func (g *Grid) SetBordersColor(color tcell.Color) *Grid { g.bordersColor = color return g }
go
func (g *Grid) SetBordersColor(color tcell.Color) *Grid { g.bordersColor = color return g }
[ "func", "(", "g", "*", "Grid", ")", "SetBordersColor", "(", "color", "tcell", ".", "Color", ")", "*", "Grid", "{", "g", ".", "bordersColor", "=", "color", "\n", "return", "g", "\n", "}" ]
// SetBordersColor sets the color of the item borders.
[ "SetBordersColor", "sets", "the", "color", "of", "the", "item", "borders", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/grid.go#L167-L170
train
rivo/tview
grid.go
RemoveItem
func (g *Grid) RemoveItem(p Primitive) *Grid { for index := len(g.items) - 1; index >= 0; index-- { if g.items[index].Item == p { g.items = append(g.items[:index], g.items[index+1:]...) } } return g }
go
func (g *Grid) RemoveItem(p Primitive) *Grid { for index := len(g.items) - 1; index >= 0; index-- { if g.items[index].Item == p { g.items = append(g.items[:index], g.items[index+1:]...) } } return g }
[ "func", "(", "g", "*", "Grid", ")", "RemoveItem", "(", "p", "Primitive", ")", "*", "Grid", "{", "for", "index", ":=", "len", "(", "g", ".", "items", ")", "-", "1", ";", "index", ">=", "0", ";", "index", "--", "{", "if", "g", ".", "items", "[", "index", "]", ".", "Item", "==", "p", "{", "g", ".", "items", "=", "append", "(", "g", ".", "items", "[", ":", "index", "]", ",", "g", ".", "items", "[", "index", "+", "1", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "return", "g", "\n", "}" ]
// RemoveItem removes all items for the given primitive from the grid, keeping // the order of the remaining items intact.
[ "RemoveItem", "removes", "all", "items", "for", "the", "given", "primitive", "from", "the", "grid", "keeping", "the", "order", "of", "the", "remaining", "items", "intact", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/grid.go#L214-L221
train
rivo/tview
grid.go
SetOffset
func (g *Grid) SetOffset(rows, columns int) *Grid { g.rowOffset, g.columnOffset = rows, columns return g }
go
func (g *Grid) SetOffset(rows, columns int) *Grid { g.rowOffset, g.columnOffset = rows, columns return g }
[ "func", "(", "g", "*", "Grid", ")", "SetOffset", "(", "rows", ",", "columns", "int", ")", "*", "Grid", "{", "g", ".", "rowOffset", ",", "g", ".", "columnOffset", "=", "rows", ",", "columns", "\n", "return", "g", "\n", "}" ]
// SetOffset sets the number of rows and columns which are skipped before // drawing the first grid cell in the top-left corner. As the grid will never // completely move off the screen, these values may be adjusted the next time // the grid is drawn. The actual position of the grid may also be adjusted such // that contained primitives that have focus are visible.
[ "SetOffset", "sets", "the", "number", "of", "rows", "and", "columns", "which", "are", "skipped", "before", "drawing", "the", "first", "grid", "cell", "in", "the", "top", "-", "left", "corner", ".", "As", "the", "grid", "will", "never", "completely", "move", "off", "the", "screen", "these", "values", "may", "be", "adjusted", "the", "next", "time", "the", "grid", "is", "drawn", ".", "The", "actual", "position", "of", "the", "grid", "may", "also", "be", "adjusted", "such", "that", "contained", "primitives", "that", "have", "focus", "are", "visible", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/grid.go#L234-L237
train
rivo/tview
demos/presentation/colors.go
Colors
func Colors(nextSlide func()) (title string, content tview.Primitive) { table := tview.NewTable(). SetBorders(true). SetBordersColor(tcell.ColorBlue). SetDoneFunc(func(key tcell.Key) { nextSlide() }) var row, column int for _, word := range strings.Split(colorsText, " ") { table.SetCellSimple(row, column, word) column++ if column > 6 { column = 0 row++ } } table.SetBorderPadding(1, 1, 2, 2). SetBorder(true). SetTitle("A [red]c[yellow]o[green]l[darkcyan]o[blue]r[darkmagenta]f[red]u[yellow]l[white] [black:red]c[:yellow]o[:green]l[:darkcyan]o[:blue]r[:darkmagenta]f[:red]u[:yellow]l[white:] [::bu]title") return "Colors", Center(78, 19, table) }
go
func Colors(nextSlide func()) (title string, content tview.Primitive) { table := tview.NewTable(). SetBorders(true). SetBordersColor(tcell.ColorBlue). SetDoneFunc(func(key tcell.Key) { nextSlide() }) var row, column int for _, word := range strings.Split(colorsText, " ") { table.SetCellSimple(row, column, word) column++ if column > 6 { column = 0 row++ } } table.SetBorderPadding(1, 1, 2, 2). SetBorder(true). SetTitle("A [red]c[yellow]o[green]l[darkcyan]o[blue]r[darkmagenta]f[red]u[yellow]l[white] [black:red]c[:yellow]o[:green]l[:darkcyan]o[:blue]r[:darkmagenta]f[:red]u[:yellow]l[white:] [::bu]title") return "Colors", Center(78, 19, table) }
[ "func", "Colors", "(", "nextSlide", "func", "(", ")", ")", "(", "title", "string", ",", "content", "tview", ".", "Primitive", ")", "{", "table", ":=", "tview", ".", "NewTable", "(", ")", ".", "SetBorders", "(", "true", ")", ".", "SetBordersColor", "(", "tcell", ".", "ColorBlue", ")", ".", "SetDoneFunc", "(", "func", "(", "key", "tcell", ".", "Key", ")", "{", "nextSlide", "(", ")", "\n", "}", ")", "\n", "var", "row", ",", "column", "int", "\n", "for", "_", ",", "word", ":=", "range", "strings", ".", "Split", "(", "colorsText", ",", "\"", "\"", ")", "{", "table", ".", "SetCellSimple", "(", "row", ",", "column", ",", "word", ")", "\n", "column", "++", "\n", "if", "column", ">", "6", "{", "column", "=", "0", "\n", "row", "++", "\n", "}", "\n", "}", "\n", "table", ".", "SetBorderPadding", "(", "1", ",", "1", ",", "2", ",", "2", ")", ".", "SetBorder", "(", "true", ")", ".", "SetTitle", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", ",", "Center", "(", "78", ",", "19", ",", "table", ")", "\n", "}" ]
// Colors demonstrates how to use colors.
[ "Colors", "demonstrates", "how", "to", "use", "colors", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/demos/presentation/colors.go#L13-L33
train
rivo/tview
demos/presentation/cover.go
Cover
func Cover(nextSlide func()) (title string, content tview.Primitive) { // What's the size of the logo? lines := strings.Split(logo, "\n") logoWidth := 0 logoHeight := len(lines) for _, line := range lines { if len(line) > logoWidth { logoWidth = len(line) } } logoBox := tview.NewTextView(). SetTextColor(tcell.ColorGreen). SetDoneFunc(func(key tcell.Key) { nextSlide() }) fmt.Fprint(logoBox, logo) // Create a frame for the subtitle and navigation infos. frame := tview.NewFrame(tview.NewBox()). SetBorders(0, 0, 0, 0, 0, 0). AddText(subtitle, true, tview.AlignCenter, tcell.ColorWhite). AddText("", true, tview.AlignCenter, tcell.ColorWhite). AddText(navigation, true, tview.AlignCenter, tcell.ColorDarkMagenta) // Create a Flex layout that centers the logo and subtitle. flex := tview.NewFlex(). SetDirection(tview.FlexRow). AddItem(tview.NewBox(), 0, 7, false). AddItem(tview.NewFlex(). AddItem(tview.NewBox(), 0, 1, false). AddItem(logoBox, logoWidth, 1, true). AddItem(tview.NewBox(), 0, 1, false), logoHeight, 1, true). AddItem(frame, 0, 10, false) return "Start", flex }
go
func Cover(nextSlide func()) (title string, content tview.Primitive) { // What's the size of the logo? lines := strings.Split(logo, "\n") logoWidth := 0 logoHeight := len(lines) for _, line := range lines { if len(line) > logoWidth { logoWidth = len(line) } } logoBox := tview.NewTextView(). SetTextColor(tcell.ColorGreen). SetDoneFunc(func(key tcell.Key) { nextSlide() }) fmt.Fprint(logoBox, logo) // Create a frame for the subtitle and navigation infos. frame := tview.NewFrame(tview.NewBox()). SetBorders(0, 0, 0, 0, 0, 0). AddText(subtitle, true, tview.AlignCenter, tcell.ColorWhite). AddText("", true, tview.AlignCenter, tcell.ColorWhite). AddText(navigation, true, tview.AlignCenter, tcell.ColorDarkMagenta) // Create a Flex layout that centers the logo and subtitle. flex := tview.NewFlex(). SetDirection(tview.FlexRow). AddItem(tview.NewBox(), 0, 7, false). AddItem(tview.NewFlex(). AddItem(tview.NewBox(), 0, 1, false). AddItem(logoBox, logoWidth, 1, true). AddItem(tview.NewBox(), 0, 1, false), logoHeight, 1, true). AddItem(frame, 0, 10, false) return "Start", flex }
[ "func", "Cover", "(", "nextSlide", "func", "(", ")", ")", "(", "title", "string", ",", "content", "tview", ".", "Primitive", ")", "{", "// What's the size of the logo?", "lines", ":=", "strings", ".", "Split", "(", "logo", ",", "\"", "\\n", "\"", ")", "\n", "logoWidth", ":=", "0", "\n", "logoHeight", ":=", "len", "(", "lines", ")", "\n", "for", "_", ",", "line", ":=", "range", "lines", "{", "if", "len", "(", "line", ")", ">", "logoWidth", "{", "logoWidth", "=", "len", "(", "line", ")", "\n", "}", "\n", "}", "\n", "logoBox", ":=", "tview", ".", "NewTextView", "(", ")", ".", "SetTextColor", "(", "tcell", ".", "ColorGreen", ")", ".", "SetDoneFunc", "(", "func", "(", "key", "tcell", ".", "Key", ")", "{", "nextSlide", "(", ")", "\n", "}", ")", "\n", "fmt", ".", "Fprint", "(", "logoBox", ",", "logo", ")", "\n\n", "// Create a frame for the subtitle and navigation infos.", "frame", ":=", "tview", ".", "NewFrame", "(", "tview", ".", "NewBox", "(", ")", ")", ".", "SetBorders", "(", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ")", ".", "AddText", "(", "subtitle", ",", "true", ",", "tview", ".", "AlignCenter", ",", "tcell", ".", "ColorWhite", ")", ".", "AddText", "(", "\"", "\"", ",", "true", ",", "tview", ".", "AlignCenter", ",", "tcell", ".", "ColorWhite", ")", ".", "AddText", "(", "navigation", ",", "true", ",", "tview", ".", "AlignCenter", ",", "tcell", ".", "ColorDarkMagenta", ")", "\n\n", "// Create a Flex layout that centers the logo and subtitle.", "flex", ":=", "tview", ".", "NewFlex", "(", ")", ".", "SetDirection", "(", "tview", ".", "FlexRow", ")", ".", "AddItem", "(", "tview", ".", "NewBox", "(", ")", ",", "0", ",", "7", ",", "false", ")", ".", "AddItem", "(", "tview", ".", "NewFlex", "(", ")", ".", "AddItem", "(", "tview", ".", "NewBox", "(", ")", ",", "0", ",", "1", ",", "false", ")", ".", "AddItem", "(", "logoBox", ",", "logoWidth", ",", "1", ",", "true", ")", ".", "AddItem", "(", "tview", ".", "NewBox", "(", ")", ",", "0", ",", "1", ",", "false", ")", ",", "logoHeight", ",", "1", ",", "true", ")", ".", "AddItem", "(", "frame", ",", "0", ",", "10", ",", "false", ")", "\n\n", "return", "\"", "\"", ",", "flex", "\n", "}" ]
// Cover returns the cover page.
[ "Cover", "returns", "the", "cover", "page", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/demos/presentation/cover.go#L26-L61
train
rivo/tview
form.go
NewForm
func NewForm() *Form { box := NewBox().SetBorderPadding(1, 1, 1, 1) f := &Form{ Box: box, itemPadding: 1, labelColor: Styles.SecondaryTextColor, fieldBackgroundColor: Styles.ContrastBackgroundColor, fieldTextColor: Styles.PrimaryTextColor, buttonBackgroundColor: Styles.ContrastBackgroundColor, buttonTextColor: Styles.PrimaryTextColor, } f.focus = f return f }
go
func NewForm() *Form { box := NewBox().SetBorderPadding(1, 1, 1, 1) f := &Form{ Box: box, itemPadding: 1, labelColor: Styles.SecondaryTextColor, fieldBackgroundColor: Styles.ContrastBackgroundColor, fieldTextColor: Styles.PrimaryTextColor, buttonBackgroundColor: Styles.ContrastBackgroundColor, buttonTextColor: Styles.PrimaryTextColor, } f.focus = f return f }
[ "func", "NewForm", "(", ")", "*", "Form", "{", "box", ":=", "NewBox", "(", ")", ".", "SetBorderPadding", "(", "1", ",", "1", ",", "1", ",", "1", ")", "\n\n", "f", ":=", "&", "Form", "{", "Box", ":", "box", ",", "itemPadding", ":", "1", ",", "labelColor", ":", "Styles", ".", "SecondaryTextColor", ",", "fieldBackgroundColor", ":", "Styles", ".", "ContrastBackgroundColor", ",", "fieldTextColor", ":", "Styles", ".", "PrimaryTextColor", ",", "buttonBackgroundColor", ":", "Styles", ".", "ContrastBackgroundColor", ",", "buttonTextColor", ":", "Styles", ".", "PrimaryTextColor", ",", "}", "\n\n", "f", ".", "focus", "=", "f", "\n\n", "return", "f", "\n", "}" ]
// NewForm returns a new form.
[ "NewForm", "returns", "a", "new", "form", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L85-L101
train
rivo/tview
form.go
SetItemPadding
func (f *Form) SetItemPadding(padding int) *Form { f.itemPadding = padding return f }
go
func (f *Form) SetItemPadding(padding int) *Form { f.itemPadding = padding return f }
[ "func", "(", "f", "*", "Form", ")", "SetItemPadding", "(", "padding", "int", ")", "*", "Form", "{", "f", ".", "itemPadding", "=", "padding", "\n", "return", "f", "\n", "}" ]
// SetItemPadding sets the number of empty rows between form items for vertical // layouts and the number of empty cells between form items for horizontal // layouts.
[ "SetItemPadding", "sets", "the", "number", "of", "empty", "rows", "between", "form", "items", "for", "vertical", "layouts", "and", "the", "number", "of", "empty", "cells", "between", "form", "items", "for", "horizontal", "layouts", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L106-L109
train
rivo/tview
form.go
SetLabelColor
func (f *Form) SetLabelColor(color tcell.Color) *Form { f.labelColor = color return f }
go
func (f *Form) SetLabelColor(color tcell.Color) *Form { f.labelColor = color return f }
[ "func", "(", "f", "*", "Form", ")", "SetLabelColor", "(", "color", "tcell", ".", "Color", ")", "*", "Form", "{", "f", ".", "labelColor", "=", "color", "\n", "return", "f", "\n", "}" ]
// SetLabelColor sets the color of the labels.
[ "SetLabelColor", "sets", "the", "color", "of", "the", "labels", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L121-L124
train
rivo/tview
form.go
SetFieldBackgroundColor
func (f *Form) SetFieldBackgroundColor(color tcell.Color) *Form { f.fieldBackgroundColor = color return f }
go
func (f *Form) SetFieldBackgroundColor(color tcell.Color) *Form { f.fieldBackgroundColor = color return f }
[ "func", "(", "f", "*", "Form", ")", "SetFieldBackgroundColor", "(", "color", "tcell", ".", "Color", ")", "*", "Form", "{", "f", ".", "fieldBackgroundColor", "=", "color", "\n", "return", "f", "\n", "}" ]
// SetFieldBackgroundColor sets the background color of the input areas.
[ "SetFieldBackgroundColor", "sets", "the", "background", "color", "of", "the", "input", "areas", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L127-L130
train
rivo/tview
form.go
SetFieldTextColor
func (f *Form) SetFieldTextColor(color tcell.Color) *Form { f.fieldTextColor = color return f }
go
func (f *Form) SetFieldTextColor(color tcell.Color) *Form { f.fieldTextColor = color return f }
[ "func", "(", "f", "*", "Form", ")", "SetFieldTextColor", "(", "color", "tcell", ".", "Color", ")", "*", "Form", "{", "f", ".", "fieldTextColor", "=", "color", "\n", "return", "f", "\n", "}" ]
// SetFieldTextColor sets the text color of the input areas.
[ "SetFieldTextColor", "sets", "the", "text", "color", "of", "the", "input", "areas", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L133-L136
train
rivo/tview
form.go
SetButtonBackgroundColor
func (f *Form) SetButtonBackgroundColor(color tcell.Color) *Form { f.buttonBackgroundColor = color return f }
go
func (f *Form) SetButtonBackgroundColor(color tcell.Color) *Form { f.buttonBackgroundColor = color return f }
[ "func", "(", "f", "*", "Form", ")", "SetButtonBackgroundColor", "(", "color", "tcell", ".", "Color", ")", "*", "Form", "{", "f", ".", "buttonBackgroundColor", "=", "color", "\n", "return", "f", "\n", "}" ]
// SetButtonBackgroundColor sets the background color of the buttons.
[ "SetButtonBackgroundColor", "sets", "the", "background", "color", "of", "the", "buttons", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L146-L149
train
rivo/tview
form.go
SetButtonTextColor
func (f *Form) SetButtonTextColor(color tcell.Color) *Form { f.buttonTextColor = color return f }
go
func (f *Form) SetButtonTextColor(color tcell.Color) *Form { f.buttonTextColor = color return f }
[ "func", "(", "f", "*", "Form", ")", "SetButtonTextColor", "(", "color", "tcell", ".", "Color", ")", "*", "Form", "{", "f", ".", "buttonTextColor", "=", "color", "\n", "return", "f", "\n", "}" ]
// SetButtonTextColor sets the color of the button texts.
[ "SetButtonTextColor", "sets", "the", "color", "of", "the", "button", "texts", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L152-L155
train
rivo/tview
form.go
AddButton
func (f *Form) AddButton(label string, selected func()) *Form { f.buttons = append(f.buttons, NewButton(label).SetSelectedFunc(selected)) return f }
go
func (f *Form) AddButton(label string, selected func()) *Form { f.buttons = append(f.buttons, NewButton(label).SetSelectedFunc(selected)) return f }
[ "func", "(", "f", "*", "Form", ")", "AddButton", "(", "label", "string", ",", "selected", "func", "(", ")", ")", "*", "Form", "{", "f", ".", "buttons", "=", "append", "(", "f", ".", "buttons", ",", "NewButton", "(", "label", ")", ".", "SetSelectedFunc", "(", "selected", ")", ")", "\n", "return", "f", "\n", "}" ]
// AddButton adds a new button to the form. The "selected" function is called // when the user selects this button. It may be nil.
[ "AddButton", "adds", "a", "new", "button", "to", "the", "form", ".", "The", "selected", "function", "is", "called", "when", "the", "user", "selects", "this", "button", ".", "It", "may", "be", "nil", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L216-L219
train
rivo/tview
form.go
RemoveButton
func (f *Form) RemoveButton(index int) *Form { f.buttons = append(f.buttons[:index], f.buttons[index+1:]...) return f }
go
func (f *Form) RemoveButton(index int) *Form { f.buttons = append(f.buttons[:index], f.buttons[index+1:]...) return f }
[ "func", "(", "f", "*", "Form", ")", "RemoveButton", "(", "index", "int", ")", "*", "Form", "{", "f", ".", "buttons", "=", "append", "(", "f", ".", "buttons", "[", ":", "index", "]", ",", "f", ".", "buttons", "[", "index", "+", "1", ":", "]", "...", ")", "\n", "return", "f", "\n", "}" ]
// RemoveButton removes the button at the specified position, starting with 0 // for the button that was added first.
[ "RemoveButton", "removes", "the", "button", "at", "the", "specified", "position", "starting", "with", "0", "for", "the", "button", "that", "was", "added", "first", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L230-L233
train
rivo/tview
form.go
GetButtonIndex
func (f *Form) GetButtonIndex(label string) int { for index, button := range f.buttons { if button.GetLabel() == label { return index } } return -1 }
go
func (f *Form) GetButtonIndex(label string) int { for index, button := range f.buttons { if button.GetLabel() == label { return index } } return -1 }
[ "func", "(", "f", "*", "Form", ")", "GetButtonIndex", "(", "label", "string", ")", "int", "{", "for", "index", ",", "button", ":=", "range", "f", ".", "buttons", "{", "if", "button", ".", "GetLabel", "(", ")", "==", "label", "{", "return", "index", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// GetButtonIndex returns the index of the button with the given label, starting // with 0 for the button that was added first. If no such label was found, -1 // is returned.
[ "GetButtonIndex", "returns", "the", "index", "of", "the", "button", "with", "the", "given", "label", "starting", "with", "0", "for", "the", "button", "that", "was", "added", "first", ".", "If", "no", "such", "label", "was", "found", "-", "1", "is", "returned", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L243-L250
train
rivo/tview
form.go
Clear
func (f *Form) Clear(includeButtons bool) *Form { f.items = nil if includeButtons { f.buttons = nil } f.focusedElement = 0 return f }
go
func (f *Form) Clear(includeButtons bool) *Form { f.items = nil if includeButtons { f.buttons = nil } f.focusedElement = 0 return f }
[ "func", "(", "f", "*", "Form", ")", "Clear", "(", "includeButtons", "bool", ")", "*", "Form", "{", "f", ".", "items", "=", "nil", "\n", "if", "includeButtons", "{", "f", ".", "buttons", "=", "nil", "\n", "}", "\n", "f", ".", "focusedElement", "=", "0", "\n", "return", "f", "\n", "}" ]
// Clear removes all input elements from the form, including the buttons if // specified.
[ "Clear", "removes", "all", "input", "elements", "from", "the", "form", "including", "the", "buttons", "if", "specified", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L254-L261
train
rivo/tview
form.go
RemoveFormItem
func (f *Form) RemoveFormItem(index int) *Form { f.items = append(f.items[:index], f.items[index+1:]...) return f }
go
func (f *Form) RemoveFormItem(index int) *Form { f.items = append(f.items[:index], f.items[index+1:]...) return f }
[ "func", "(", "f", "*", "Form", ")", "RemoveFormItem", "(", "index", "int", ")", "*", "Form", "{", "f", ".", "items", "=", "append", "(", "f", ".", "items", "[", ":", "index", "]", ",", "f", ".", "items", "[", "index", "+", "1", ":", "]", "...", ")", "\n", "return", "f", "\n", "}" ]
// RemoveFormItem removes the form element at the given position, starting with // index 0. Elements are referenced in the order they were added. Buttons are // not included.
[ "RemoveFormItem", "removes", "the", "form", "element", "at", "the", "given", "position", "starting", "with", "index", "0", ".", "Elements", "are", "referenced", "in", "the", "order", "they", "were", "added", ".", "Buttons", "are", "not", "included", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L288-L291
train
rivo/tview
form.go
GetFormItemByLabel
func (f *Form) GetFormItemByLabel(label string) FormItem { for _, item := range f.items { if item.GetLabel() == label { return item } } return nil }
go
func (f *Form) GetFormItemByLabel(label string) FormItem { for _, item := range f.items { if item.GetLabel() == label { return item } } return nil }
[ "func", "(", "f", "*", "Form", ")", "GetFormItemByLabel", "(", "label", "string", ")", "FormItem", "{", "for", "_", ",", "item", ":=", "range", "f", ".", "items", "{", "if", "item", ".", "GetLabel", "(", ")", "==", "label", "{", "return", "item", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetFormItemByLabel returns the first form element with the given label. If // no such element is found, nil is returned. Buttons are not searched and will // therefore not be returned.
[ "GetFormItemByLabel", "returns", "the", "first", "form", "element", "with", "the", "given", "label", ".", "If", "no", "such", "element", "is", "found", "nil", "is", "returned", ".", "Buttons", "are", "not", "searched", "and", "will", "therefore", "not", "be", "returned", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L296-L303
train
rivo/tview
form.go
GetFormItemIndex
func (f *Form) GetFormItemIndex(label string) int { for index, item := range f.items { if item.GetLabel() == label { return index } } return -1 }
go
func (f *Form) GetFormItemIndex(label string) int { for index, item := range f.items { if item.GetLabel() == label { return index } } return -1 }
[ "func", "(", "f", "*", "Form", ")", "GetFormItemIndex", "(", "label", "string", ")", "int", "{", "for", "index", ",", "item", ":=", "range", "f", ".", "items", "{", "if", "item", ".", "GetLabel", "(", ")", "==", "label", "{", "return", "index", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// GetFormItemIndex returns the index of the first form element with the given // label. If no such element is found, -1 is returned. Buttons are not searched // and will therefore not be returned.
[ "GetFormItemIndex", "returns", "the", "index", "of", "the", "first", "form", "element", "with", "the", "given", "label", ".", "If", "no", "such", "element", "is", "found", "-", "1", "is", "returned", ".", "Buttons", "are", "not", "searched", "and", "will", "therefore", "not", "be", "returned", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/form.go#L308-L315
train
rivo/tview
demos/presentation/end.go
End
func End(nextSlide func()) (title string, content tview.Primitive) { textView := tview.NewTextView().SetDoneFunc(func(key tcell.Key) { nextSlide() }) url := "https://github.com/rivo/tview" fmt.Fprint(textView, url) return "End", Center(len(url), 1, textView) }
go
func End(nextSlide func()) (title string, content tview.Primitive) { textView := tview.NewTextView().SetDoneFunc(func(key tcell.Key) { nextSlide() }) url := "https://github.com/rivo/tview" fmt.Fprint(textView, url) return "End", Center(len(url), 1, textView) }
[ "func", "End", "(", "nextSlide", "func", "(", ")", ")", "(", "title", "string", ",", "content", "tview", ".", "Primitive", ")", "{", "textView", ":=", "tview", ".", "NewTextView", "(", ")", ".", "SetDoneFunc", "(", "func", "(", "key", "tcell", ".", "Key", ")", "{", "nextSlide", "(", ")", "\n", "}", ")", "\n", "url", ":=", "\"", "\"", "\n", "fmt", ".", "Fprint", "(", "textView", ",", "url", ")", "\n", "return", "\"", "\"", ",", "Center", "(", "len", "(", "url", ")", ",", "1", ",", "textView", ")", "\n", "}" ]
// End shows the final slide.
[ "End", "shows", "the", "final", "slide", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/demos/presentation/end.go#L11-L18
train
rivo/tview
semigraphics.go
PrintJoinedSemigraphics
func PrintJoinedSemigraphics(screen tcell.Screen, x, y int, ch rune, color tcell.Color) { previous, _, style, _ := screen.GetContent(x, y) style = style.Foreground(color) // What's the resulting rune? var result rune if ch == previous { result = ch } else { if ch < previous { previous, ch = ch, previous } result = SemigraphicJoints[string([]rune{previous, ch})] } if result == 0 { result = ch } // We only print something if we have something. screen.SetContent(x, y, result, nil, style) }
go
func PrintJoinedSemigraphics(screen tcell.Screen, x, y int, ch rune, color tcell.Color) { previous, _, style, _ := screen.GetContent(x, y) style = style.Foreground(color) // What's the resulting rune? var result rune if ch == previous { result = ch } else { if ch < previous { previous, ch = ch, previous } result = SemigraphicJoints[string([]rune{previous, ch})] } if result == 0 { result = ch } // We only print something if we have something. screen.SetContent(x, y, result, nil, style) }
[ "func", "PrintJoinedSemigraphics", "(", "screen", "tcell", ".", "Screen", ",", "x", ",", "y", "int", ",", "ch", "rune", ",", "color", "tcell", ".", "Color", ")", "{", "previous", ",", "_", ",", "style", ",", "_", ":=", "screen", ".", "GetContent", "(", "x", ",", "y", ")", "\n", "style", "=", "style", ".", "Foreground", "(", "color", ")", "\n\n", "// What's the resulting rune?", "var", "result", "rune", "\n", "if", "ch", "==", "previous", "{", "result", "=", "ch", "\n", "}", "else", "{", "if", "ch", "<", "previous", "{", "previous", ",", "ch", "=", "ch", ",", "previous", "\n", "}", "\n", "result", "=", "SemigraphicJoints", "[", "string", "(", "[", "]", "rune", "{", "previous", ",", "ch", "}", ")", "]", "\n", "}", "\n", "if", "result", "==", "0", "{", "result", "=", "ch", "\n", "}", "\n\n", "// We only print something if we have something.", "screen", ".", "SetContent", "(", "x", ",", "y", ",", "result", ",", "nil", ",", "style", ")", "\n", "}" ]
// PrintJoinedSemigraphics prints a semigraphics rune into the screen at the given // position with the given color, joining it with any existing semigraphics // rune. Background colors are preserved. At this point, only regular single // line borders are supported.
[ "PrintJoinedSemigraphics", "prints", "a", "semigraphics", "rune", "into", "the", "screen", "at", "the", "given", "position", "with", "the", "given", "color", "joining", "it", "with", "any", "existing", "semigraphics", "rune", ".", "Background", "colors", "are", "preserved", ".", "At", "this", "point", "only", "regular", "single", "line", "borders", "are", "supported", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/semigraphics.go#L276-L296
train
rivo/tview
application.go
NewApplication
func NewApplication() *Application { return &Application{ events: make(chan tcell.Event, queueSize), updates: make(chan func(), queueSize), screenReplacement: make(chan tcell.Screen, 1), } }
go
func NewApplication() *Application { return &Application{ events: make(chan tcell.Event, queueSize), updates: make(chan func(), queueSize), screenReplacement: make(chan tcell.Screen, 1), } }
[ "func", "NewApplication", "(", ")", "*", "Application", "{", "return", "&", "Application", "{", "events", ":", "make", "(", "chan", "tcell", ".", "Event", ",", "queueSize", ")", ",", "updates", ":", "make", "(", "chan", "func", "(", ")", ",", "queueSize", ")", ",", "screenReplacement", ":", "make", "(", "chan", "tcell", ".", "Screen", ",", "1", ")", ",", "}", "\n", "}" ]
// NewApplication creates and returns a new application.
[ "NewApplication", "creates", "and", "returns", "a", "new", "application", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/application.go#L68-L74
train
rivo/tview
application.go
Suspend
func (a *Application) Suspend(f func()) bool { a.RLock() screen := a.screen a.RUnlock() if screen == nil { return false // Screen has not yet been initialized. } // Enter suspended mode. screen.Fini() // Wait for "f" to return. f() // Make a new screen. var err error screen, err = tcell.NewScreen() if err != nil { panic(err) } a.screenReplacement <- screen // One key event will get lost, see https://github.com/gdamore/tcell/issues/194 // Continue application loop. return true }
go
func (a *Application) Suspend(f func()) bool { a.RLock() screen := a.screen a.RUnlock() if screen == nil { return false // Screen has not yet been initialized. } // Enter suspended mode. screen.Fini() // Wait for "f" to return. f() // Make a new screen. var err error screen, err = tcell.NewScreen() if err != nil { panic(err) } a.screenReplacement <- screen // One key event will get lost, see https://github.com/gdamore/tcell/issues/194 // Continue application loop. return true }
[ "func", "(", "a", "*", "Application", ")", "Suspend", "(", "f", "func", "(", ")", ")", "bool", "{", "a", ".", "RLock", "(", ")", "\n", "screen", ":=", "a", ".", "screen", "\n", "a", ".", "RUnlock", "(", ")", "\n", "if", "screen", "==", "nil", "{", "return", "false", "// Screen has not yet been initialized.", "\n", "}", "\n\n", "// Enter suspended mode.", "screen", ".", "Fini", "(", ")", "\n\n", "// Wait for \"f\" to return.", "f", "(", ")", "\n\n", "// Make a new screen.", "var", "err", "error", "\n", "screen", ",", "err", "=", "tcell", ".", "NewScreen", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "a", ".", "screenReplacement", "<-", "screen", "\n", "// One key event will get lost, see https://github.com/gdamore/tcell/issues/194", "// Continue application loop.", "return", "true", "\n", "}" ]
// Suspend temporarily suspends the application by exiting terminal UI mode and // invoking the provided function "f". When "f" returns, terminal UI mode is // entered again and the application resumes. // // A return value of true indicates that the application was suspended and "f" // was called. If false is returned, the application was already suspended, // terminal UI mode was not exited, and "f" was not called.
[ "Suspend", "temporarily", "suspends", "the", "application", "by", "exiting", "terminal", "UI", "mode", "and", "invoking", "the", "provided", "function", "f", ".", "When", "f", "returns", "terminal", "UI", "mode", "is", "entered", "again", "and", "the", "application", "resumes", ".", "A", "return", "value", "of", "true", "indicates", "that", "the", "application", "was", "suspended", "and", "f", "was", "called", ".", "If", "false", "is", "returned", "the", "application", "was", "already", "suspended", "terminal", "UI", "mode", "was", "not", "exited", "and", "f", "was", "not", "called", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/application.go#L284-L309
train
rivo/tview
application.go
SetAfterDrawFunc
func (a *Application) SetAfterDrawFunc(handler func(screen tcell.Screen)) *Application { a.afterDraw = handler return a }
go
func (a *Application) SetAfterDrawFunc(handler func(screen tcell.Screen)) *Application { a.afterDraw = handler return a }
[ "func", "(", "a", "*", "Application", ")", "SetAfterDrawFunc", "(", "handler", "func", "(", "screen", "tcell", ".", "Screen", ")", ")", "*", "Application", "{", "a", ".", "afterDraw", "=", "handler", "\n", "return", "a", "\n", "}" ]
// SetAfterDrawFunc installs a callback function which is invoked after the root // primitive was drawn during screen updates. // // Provide nil to uninstall the callback function.
[ "SetAfterDrawFunc", "installs", "a", "callback", "function", "which", "is", "invoked", "after", "the", "root", "primitive", "was", "drawn", "during", "screen", "updates", ".", "Provide", "nil", "to", "uninstall", "the", "callback", "function", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/application.go#L400-L403
train
rivo/tview
application.go
ResizeToFullScreen
func (a *Application) ResizeToFullScreen(p Primitive) *Application { a.RLock() width, height := a.screen.Size() a.RUnlock() p.SetRect(0, 0, width, height) return a }
go
func (a *Application) ResizeToFullScreen(p Primitive) *Application { a.RLock() width, height := a.screen.Size() a.RUnlock() p.SetRect(0, 0, width, height) return a }
[ "func", "(", "a", "*", "Application", ")", "ResizeToFullScreen", "(", "p", "Primitive", ")", "*", "Application", "{", "a", ".", "RLock", "(", ")", "\n", "width", ",", "height", ":=", "a", ".", "screen", ".", "Size", "(", ")", "\n", "a", ".", "RUnlock", "(", ")", "\n", "p", ".", "SetRect", "(", "0", ",", "0", ",", "width", ",", "height", ")", "\n", "return", "a", "\n", "}" ]
// ResizeToFullScreen resizes the given primitive such that it fills the entire // screen.
[ "ResizeToFullScreen", "resizes", "the", "given", "primitive", "such", "that", "it", "fills", "the", "entire", "screen", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/application.go#L434-L440
train
rivo/tview
application.go
GetFocus
func (a *Application) GetFocus() Primitive { a.RLock() defer a.RUnlock() return a.focus }
go
func (a *Application) GetFocus() Primitive { a.RLock() defer a.RUnlock() return a.focus }
[ "func", "(", "a", "*", "Application", ")", "GetFocus", "(", ")", "Primitive", "{", "a", ".", "RLock", "(", ")", "\n", "defer", "a", ".", "RUnlock", "(", ")", "\n", "return", "a", ".", "focus", "\n", "}" ]
// GetFocus returns the primitive which has the current focus. If none has it, // nil is returned.
[ "GetFocus", "returns", "the", "primitive", "which", "has", "the", "current", "focus", ".", "If", "none", "has", "it", "nil", "is", "returned", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/application.go#L469-L473
train
rivo/tview
application.go
QueueEvent
func (a *Application) QueueEvent(event tcell.Event) *Application { a.events <- event return a }
go
func (a *Application) QueueEvent(event tcell.Event) *Application { a.events <- event return a }
[ "func", "(", "a", "*", "Application", ")", "QueueEvent", "(", "event", "tcell", ".", "Event", ")", "*", "Application", "{", "a", ".", "events", "<-", "event", "\n", "return", "a", "\n", "}" ]
// QueueEvent sends an event to the Application event loop. // // It is not recommended for event to be nil.
[ "QueueEvent", "sends", "an", "event", "to", "the", "Application", "event", "loop", ".", "It", "is", "not", "recommended", "for", "event", "to", "be", "nil", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/application.go#L502-L505
train
rivo/tview
pages.go
NewPages
func NewPages() *Pages { p := &Pages{ Box: NewBox(), } p.focus = p return p }
go
func NewPages() *Pages { p := &Pages{ Box: NewBox(), } p.focus = p return p }
[ "func", "NewPages", "(", ")", "*", "Pages", "{", "p", ":=", "&", "Pages", "{", "Box", ":", "NewBox", "(", ")", ",", "}", "\n", "p", ".", "focus", "=", "p", "\n", "return", "p", "\n", "}" ]
// NewPages returns a new Pages object.
[ "NewPages", "returns", "a", "new", "Pages", "object", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/pages.go#L36-L42
train
rivo/tview
pages.go
RemovePage
func (p *Pages) RemovePage(name string) *Pages { var isVisible bool hasFocus := p.HasFocus() for index, page := range p.pages { if page.Name == name { isVisible = page.Visible p.pages = append(p.pages[:index], p.pages[index+1:]...) if page.Visible && p.changed != nil { p.changed() } break } } if isVisible { for index, page := range p.pages { if index < len(p.pages)-1 { if page.Visible { break // There is a remaining visible page. } } else { page.Visible = true // We need at least one visible page. } } } if hasFocus { p.Focus(p.setFocus) } return p }
go
func (p *Pages) RemovePage(name string) *Pages { var isVisible bool hasFocus := p.HasFocus() for index, page := range p.pages { if page.Name == name { isVisible = page.Visible p.pages = append(p.pages[:index], p.pages[index+1:]...) if page.Visible && p.changed != nil { p.changed() } break } } if isVisible { for index, page := range p.pages { if index < len(p.pages)-1 { if page.Visible { break // There is a remaining visible page. } } else { page.Visible = true // We need at least one visible page. } } } if hasFocus { p.Focus(p.setFocus) } return p }
[ "func", "(", "p", "*", "Pages", ")", "RemovePage", "(", "name", "string", ")", "*", "Pages", "{", "var", "isVisible", "bool", "\n", "hasFocus", ":=", "p", ".", "HasFocus", "(", ")", "\n", "for", "index", ",", "page", ":=", "range", "p", ".", "pages", "{", "if", "page", ".", "Name", "==", "name", "{", "isVisible", "=", "page", ".", "Visible", "\n", "p", ".", "pages", "=", "append", "(", "p", ".", "pages", "[", ":", "index", "]", ",", "p", ".", "pages", "[", "index", "+", "1", ":", "]", "...", ")", "\n", "if", "page", ".", "Visible", "&&", "p", ".", "changed", "!=", "nil", "{", "p", ".", "changed", "(", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "isVisible", "{", "for", "index", ",", "page", ":=", "range", "p", ".", "pages", "{", "if", "index", "<", "len", "(", "p", ".", "pages", ")", "-", "1", "{", "if", "page", ".", "Visible", "{", "break", "// There is a remaining visible page.", "\n", "}", "\n", "}", "else", "{", "page", ".", "Visible", "=", "true", "// We need at least one visible page.", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "hasFocus", "{", "p", ".", "Focus", "(", "p", ".", "setFocus", ")", "\n", "}", "\n", "return", "p", "\n", "}" ]
// RemovePage removes the page with the given name. If that page was the only // visible page, visibility is assigned to the last page.
[ "RemovePage", "removes", "the", "page", "with", "the", "given", "name", ".", "If", "that", "page", "was", "the", "only", "visible", "page", "visibility", "is", "assigned", "to", "the", "last", "page", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/pages.go#L88-L116
train
rivo/tview
pages.go
HasPage
func (p *Pages) HasPage(name string) bool { for _, page := range p.pages { if page.Name == name { return true } } return false }
go
func (p *Pages) HasPage(name string) bool { for _, page := range p.pages { if page.Name == name { return true } } return false }
[ "func", "(", "p", "*", "Pages", ")", "HasPage", "(", "name", "string", ")", "bool", "{", "for", "_", ",", "page", ":=", "range", "p", ".", "pages", "{", "if", "page", ".", "Name", "==", "name", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasPage returns true if a page with the given name exists in this object.
[ "HasPage", "returns", "true", "if", "a", "page", "with", "the", "given", "name", "exists", "in", "this", "object", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/pages.go#L119-L126
train
rivo/tview
textview.go
NewTextView
func NewTextView() *TextView { return &TextView{ Box: NewBox(), highlights: make(map[string]struct{}), lineOffset: -1, scrollable: true, align: AlignLeft, wrap: true, textColor: Styles.PrimaryTextColor, regions: false, dynamicColors: false, } }
go
func NewTextView() *TextView { return &TextView{ Box: NewBox(), highlights: make(map[string]struct{}), lineOffset: -1, scrollable: true, align: AlignLeft, wrap: true, textColor: Styles.PrimaryTextColor, regions: false, dynamicColors: false, } }
[ "func", "NewTextView", "(", ")", "*", "TextView", "{", "return", "&", "TextView", "{", "Box", ":", "NewBox", "(", ")", ",", "highlights", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "lineOffset", ":", "-", "1", ",", "scrollable", ":", "true", ",", "align", ":", "AlignLeft", ",", "wrap", ":", "true", ",", "textColor", ":", "Styles", ".", "PrimaryTextColor", ",", "regions", ":", "false", ",", "dynamicColors", ":", "false", ",", "}", "\n", "}" ]
// NewTextView returns a new text view.
[ "NewTextView", "returns", "a", "new", "text", "view", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L175-L187
train
rivo/tview
textview.go
SetScrollable
func (t *TextView) SetScrollable(scrollable bool) *TextView { t.scrollable = scrollable if !scrollable { t.trackEnd = true } return t }
go
func (t *TextView) SetScrollable(scrollable bool) *TextView { t.scrollable = scrollable if !scrollable { t.trackEnd = true } return t }
[ "func", "(", "t", "*", "TextView", ")", "SetScrollable", "(", "scrollable", "bool", ")", "*", "TextView", "{", "t", ".", "scrollable", "=", "scrollable", "\n", "if", "!", "scrollable", "{", "t", ".", "trackEnd", "=", "true", "\n", "}", "\n", "return", "t", "\n", "}" ]
// SetScrollable sets the flag that decides whether or not the text view is // scrollable. If true, text is kept in a buffer and can be navigated.
[ "SetScrollable", "sets", "the", "flag", "that", "decides", "whether", "or", "not", "the", "text", "view", "is", "scrollable", ".", "If", "true", "text", "is", "kept", "in", "a", "buffer", "and", "can", "be", "navigated", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L191-L197
train
rivo/tview
textview.go
SetWrap
func (t *TextView) SetWrap(wrap bool) *TextView { if t.wrap != wrap { t.index = nil } t.wrap = wrap return t }
go
func (t *TextView) SetWrap(wrap bool) *TextView { if t.wrap != wrap { t.index = nil } t.wrap = wrap return t }
[ "func", "(", "t", "*", "TextView", ")", "SetWrap", "(", "wrap", "bool", ")", "*", "TextView", "{", "if", "t", ".", "wrap", "!=", "wrap", "{", "t", ".", "index", "=", "nil", "\n", "}", "\n", "t", ".", "wrap", "=", "wrap", "\n", "return", "t", "\n", "}" ]
// SetWrap sets the flag that, if true, leads to lines that are longer than the // available width being wrapped onto the next line. If false, any characters // beyond the available width are not displayed.
[ "SetWrap", "sets", "the", "flag", "that", "if", "true", "leads", "to", "lines", "that", "are", "longer", "than", "the", "available", "width", "being", "wrapped", "onto", "the", "next", "line", ".", "If", "false", "any", "characters", "beyond", "the", "available", "width", "are", "not", "displayed", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L202-L208
train
rivo/tview
textview.go
SetTextAlign
func (t *TextView) SetTextAlign(align int) *TextView { if t.align != align { t.index = nil } t.align = align return t }
go
func (t *TextView) SetTextAlign(align int) *TextView { if t.align != align { t.index = nil } t.align = align return t }
[ "func", "(", "t", "*", "TextView", ")", "SetTextAlign", "(", "align", "int", ")", "*", "TextView", "{", "if", "t", ".", "align", "!=", "align", "{", "t", ".", "index", "=", "nil", "\n", "}", "\n", "t", ".", "align", "=", "align", "\n", "return", "t", "\n", "}" ]
// SetTextAlign sets the text alignment within the text view. This must be // either AlignLeft, AlignCenter, or AlignRight.
[ "SetTextAlign", "sets", "the", "text", "alignment", "within", "the", "text", "view", ".", "This", "must", "be", "either", "AlignLeft", "AlignCenter", "or", "AlignRight", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L225-L231
train
rivo/tview
textview.go
SetText
func (t *TextView) SetText(text string) *TextView { t.Clear() fmt.Fprint(t, text) return t }
go
func (t *TextView) SetText(text string) *TextView { t.Clear() fmt.Fprint(t, text) return t }
[ "func", "(", "t", "*", "TextView", ")", "SetText", "(", "text", "string", ")", "*", "TextView", "{", "t", ".", "Clear", "(", ")", "\n", "fmt", ".", "Fprint", "(", "t", ",", "text", ")", "\n", "return", "t", "\n", "}" ]
// SetText sets the text of this text view to the provided string. Previously // contained text will be removed.
[ "SetText", "sets", "the", "text", "of", "this", "text", "view", "to", "the", "provided", "string", ".", "Previously", "contained", "text", "will", "be", "removed", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L243-L247
train
rivo/tview
textview.go
SetDynamicColors
func (t *TextView) SetDynamicColors(dynamic bool) *TextView { if t.dynamicColors != dynamic { t.index = nil } t.dynamicColors = dynamic return t }
go
func (t *TextView) SetDynamicColors(dynamic bool) *TextView { if t.dynamicColors != dynamic { t.index = nil } t.dynamicColors = dynamic return t }
[ "func", "(", "t", "*", "TextView", ")", "SetDynamicColors", "(", "dynamic", "bool", ")", "*", "TextView", "{", "if", "t", ".", "dynamicColors", "!=", "dynamic", "{", "t", ".", "index", "=", "nil", "\n", "}", "\n", "t", ".", "dynamicColors", "=", "dynamic", "\n", "return", "t", "\n", "}" ]
// SetDynamicColors sets the flag that allows the text color to be changed // dynamically. See class description for details.
[ "SetDynamicColors", "sets", "the", "flag", "that", "allows", "the", "text", "color", "to", "be", "changed", "dynamically", ".", "See", "class", "description", "for", "details", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L279-L285
train
rivo/tview
textview.go
SetRegions
func (t *TextView) SetRegions(regions bool) *TextView { if t.regions != regions { t.index = nil } t.regions = regions return t }
go
func (t *TextView) SetRegions(regions bool) *TextView { if t.regions != regions { t.index = nil } t.regions = regions return t }
[ "func", "(", "t", "*", "TextView", ")", "SetRegions", "(", "regions", "bool", ")", "*", "TextView", "{", "if", "t", ".", "regions", "!=", "regions", "{", "t", ".", "index", "=", "nil", "\n", "}", "\n", "t", ".", "regions", "=", "regions", "\n", "return", "t", "\n", "}" ]
// SetRegions sets the flag that allows to define regions in the text. See class // description for details.
[ "SetRegions", "sets", "the", "flag", "that", "allows", "to", "define", "regions", "in", "the", "text", ".", "See", "class", "description", "for", "details", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L289-L295
train
rivo/tview
textview.go
ScrollToBeginning
func (t *TextView) ScrollToBeginning() *TextView { if !t.scrollable { return t } t.trackEnd = false t.lineOffset = 0 t.columnOffset = 0 return t }
go
func (t *TextView) ScrollToBeginning() *TextView { if !t.scrollable { return t } t.trackEnd = false t.lineOffset = 0 t.columnOffset = 0 return t }
[ "func", "(", "t", "*", "TextView", ")", "ScrollToBeginning", "(", ")", "*", "TextView", "{", "if", "!", "t", ".", "scrollable", "{", "return", "t", "\n", "}", "\n", "t", ".", "trackEnd", "=", "false", "\n", "t", ".", "lineOffset", "=", "0", "\n", "t", ".", "columnOffset", "=", "0", "\n", "return", "t", "\n", "}" ]
// ScrollToBeginning scrolls to the top left corner of the text if the text view // is scrollable.
[ "ScrollToBeginning", "scrolls", "to", "the", "top", "left", "corner", "of", "the", "text", "if", "the", "text", "view", "is", "scrollable", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L337-L345
train
rivo/tview
textview.go
ScrollToEnd
func (t *TextView) ScrollToEnd() *TextView { if !t.scrollable { return t } t.trackEnd = true t.columnOffset = 0 return t }
go
func (t *TextView) ScrollToEnd() *TextView { if !t.scrollable { return t } t.trackEnd = true t.columnOffset = 0 return t }
[ "func", "(", "t", "*", "TextView", ")", "ScrollToEnd", "(", ")", "*", "TextView", "{", "if", "!", "t", ".", "scrollable", "{", "return", "t", "\n", "}", "\n", "t", ".", "trackEnd", "=", "true", "\n", "t", ".", "columnOffset", "=", "0", "\n", "return", "t", "\n", "}" ]
// ScrollToEnd scrolls to the bottom left corner of the text if the text view // is scrollable. Adding new rows to the end of the text view will cause it to // scroll with the new data.
[ "ScrollToEnd", "scrolls", "to", "the", "bottom", "left", "corner", "of", "the", "text", "if", "the", "text", "view", "is", "scrollable", ".", "Adding", "new", "rows", "to", "the", "end", "of", "the", "text", "view", "will", "cause", "it", "to", "scroll", "with", "the", "new", "data", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L350-L357
train
rivo/tview
textview.go
GetScrollOffset
func (t *TextView) GetScrollOffset() (row, column int) { return t.lineOffset, t.columnOffset }
go
func (t *TextView) GetScrollOffset() (row, column int) { return t.lineOffset, t.columnOffset }
[ "func", "(", "t", "*", "TextView", ")", "GetScrollOffset", "(", ")", "(", "row", ",", "column", "int", ")", "{", "return", "t", ".", "lineOffset", ",", "t", ".", "columnOffset", "\n", "}" ]
// GetScrollOffset returns the number of rows and columns that are skipped at // the top left corner when the text view has been scrolled.
[ "GetScrollOffset", "returns", "the", "number", "of", "rows", "and", "columns", "that", "are", "skipped", "at", "the", "top", "left", "corner", "when", "the", "text", "view", "has", "been", "scrolled", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L361-L363
train
rivo/tview
textview.go
Clear
func (t *TextView) Clear() *TextView { t.buffer = nil t.recentBytes = nil t.index = nil return t }
go
func (t *TextView) Clear() *TextView { t.buffer = nil t.recentBytes = nil t.index = nil return t }
[ "func", "(", "t", "*", "TextView", ")", "Clear", "(", ")", "*", "TextView", "{", "t", ".", "buffer", "=", "nil", "\n", "t", ".", "recentBytes", "=", "nil", "\n", "t", ".", "index", "=", "nil", "\n", "return", "t", "\n", "}" ]
// Clear removes all text from the buffer.
[ "Clear", "removes", "all", "text", "from", "the", "buffer", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L366-L371
train
rivo/tview
textview.go
Highlight
func (t *TextView) Highlight(regionIDs ...string) *TextView { t.highlights = make(map[string]struct{}) for _, id := range regionIDs { if id == "" { continue } t.highlights[id] = struct{}{} } t.index = nil return t }
go
func (t *TextView) Highlight(regionIDs ...string) *TextView { t.highlights = make(map[string]struct{}) for _, id := range regionIDs { if id == "" { continue } t.highlights[id] = struct{}{} } t.index = nil return t }
[ "func", "(", "t", "*", "TextView", ")", "Highlight", "(", "regionIDs", "...", "string", ")", "*", "TextView", "{", "t", ".", "highlights", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "id", ":=", "range", "regionIDs", "{", "if", "id", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "t", ".", "highlights", "[", "id", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "t", ".", "index", "=", "nil", "\n", "return", "t", "\n", "}" ]
// Highlight specifies which regions should be highlighted. See class // description for details on regions. Empty region strings are ignored. // // Text in highlighted regions will be drawn inverted, i.e. with their // background and foreground colors swapped. // // Calling this function will remove any previous highlights. To remove all // highlights, call this function without any arguments.
[ "Highlight", "specifies", "which", "regions", "should", "be", "highlighted", ".", "See", "class", "description", "for", "details", "on", "regions", ".", "Empty", "region", "strings", "are", "ignored", ".", "Text", "in", "highlighted", "regions", "will", "be", "drawn", "inverted", "i", ".", "e", ".", "with", "their", "background", "and", "foreground", "colors", "swapped", ".", "Calling", "this", "function", "will", "remove", "any", "previous", "highlights", ".", "To", "remove", "all", "highlights", "call", "this", "function", "without", "any", "arguments", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L381-L391
train
rivo/tview
textview.go
GetHighlights
func (t *TextView) GetHighlights() (regionIDs []string) { for id := range t.highlights { regionIDs = append(regionIDs, id) } return }
go
func (t *TextView) GetHighlights() (regionIDs []string) { for id := range t.highlights { regionIDs = append(regionIDs, id) } return }
[ "func", "(", "t", "*", "TextView", ")", "GetHighlights", "(", ")", "(", "regionIDs", "[", "]", "string", ")", "{", "for", "id", ":=", "range", "t", ".", "highlights", "{", "regionIDs", "=", "append", "(", "regionIDs", ",", "id", ")", "\n", "}", "\n", "return", "\n", "}" ]
// GetHighlights returns the IDs of all currently highlighted regions.
[ "GetHighlights", "returns", "the", "IDs", "of", "all", "currently", "highlighted", "regions", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L394-L399
train
rivo/tview
textview.go
ScrollToHighlight
func (t *TextView) ScrollToHighlight() *TextView { if len(t.highlights) == 0 || !t.scrollable || !t.regions { return t } t.index = nil t.scrollToHighlights = true t.trackEnd = false return t }
go
func (t *TextView) ScrollToHighlight() *TextView { if len(t.highlights) == 0 || !t.scrollable || !t.regions { return t } t.index = nil t.scrollToHighlights = true t.trackEnd = false return t }
[ "func", "(", "t", "*", "TextView", ")", "ScrollToHighlight", "(", ")", "*", "TextView", "{", "if", "len", "(", "t", ".", "highlights", ")", "==", "0", "||", "!", "t", ".", "scrollable", "||", "!", "t", ".", "regions", "{", "return", "t", "\n", "}", "\n", "t", ".", "index", "=", "nil", "\n", "t", ".", "scrollToHighlights", "=", "true", "\n", "t", ".", "trackEnd", "=", "false", "\n", "return", "t", "\n", "}" ]
// ScrollToHighlight will cause the visible area to be scrolled so that the // highlighted regions appear in the visible area of the text view. This // repositioning happens the next time the text view is drawn. It happens only // once so you will need to call this function repeatedly to always keep // highlighted regions in view. // // Nothing happens if there are no highlighted regions or if the text view is // not scrollable.
[ "ScrollToHighlight", "will", "cause", "the", "visible", "area", "to", "be", "scrolled", "so", "that", "the", "highlighted", "regions", "appear", "in", "the", "visible", "area", "of", "the", "text", "view", ".", "This", "repositioning", "happens", "the", "next", "time", "the", "text", "view", "is", "drawn", ".", "It", "happens", "only", "once", "so", "you", "will", "need", "to", "call", "this", "function", "repeatedly", "to", "always", "keep", "highlighted", "regions", "in", "view", ".", "Nothing", "happens", "if", "there", "are", "no", "highlighted", "regions", "or", "if", "the", "text", "view", "is", "not", "scrollable", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L409-L417
train
rivo/tview
textview.go
GetRegionText
func (t *TextView) GetRegionText(regionID string) string { if !t.regions || regionID == "" { return "" } var ( buffer bytes.Buffer currentRegionID string ) for _, str := range t.buffer { // Find all color tags in this line. var colorTagIndices [][]int if t.dynamicColors { colorTagIndices = colorPattern.FindAllStringIndex(str, -1) } // Find all regions in this line. var ( regionIndices [][]int regions [][]string ) if t.regions { regionIndices = regionPattern.FindAllStringIndex(str, -1) regions = regionPattern.FindAllStringSubmatch(str, -1) } // Analyze this line. var currentTag, currentRegion int for pos, ch := range str { // Skip any color tags. if currentTag < len(colorTagIndices) && pos >= colorTagIndices[currentTag][0] && pos < colorTagIndices[currentTag][1] { if pos == colorTagIndices[currentTag][1]-1 { currentTag++ } continue } // Skip any regions. if currentRegion < len(regionIndices) && pos >= regionIndices[currentRegion][0] && pos < regionIndices[currentRegion][1] { if pos == regionIndices[currentRegion][1]-1 { if currentRegionID == regionID { // This is the end of the requested region. We're done. return buffer.String() } currentRegionID = regions[currentRegion][1] currentRegion++ } continue } // Add this rune. if currentRegionID == regionID { buffer.WriteRune(ch) } } // Add newline. if currentRegionID == regionID { buffer.WriteRune('\n') } } return escapePattern.ReplaceAllString(buffer.String(), `[$1$2]`) }
go
func (t *TextView) GetRegionText(regionID string) string { if !t.regions || regionID == "" { return "" } var ( buffer bytes.Buffer currentRegionID string ) for _, str := range t.buffer { // Find all color tags in this line. var colorTagIndices [][]int if t.dynamicColors { colorTagIndices = colorPattern.FindAllStringIndex(str, -1) } // Find all regions in this line. var ( regionIndices [][]int regions [][]string ) if t.regions { regionIndices = regionPattern.FindAllStringIndex(str, -1) regions = regionPattern.FindAllStringSubmatch(str, -1) } // Analyze this line. var currentTag, currentRegion int for pos, ch := range str { // Skip any color tags. if currentTag < len(colorTagIndices) && pos >= colorTagIndices[currentTag][0] && pos < colorTagIndices[currentTag][1] { if pos == colorTagIndices[currentTag][1]-1 { currentTag++ } continue } // Skip any regions. if currentRegion < len(regionIndices) && pos >= regionIndices[currentRegion][0] && pos < regionIndices[currentRegion][1] { if pos == regionIndices[currentRegion][1]-1 { if currentRegionID == regionID { // This is the end of the requested region. We're done. return buffer.String() } currentRegionID = regions[currentRegion][1] currentRegion++ } continue } // Add this rune. if currentRegionID == regionID { buffer.WriteRune(ch) } } // Add newline. if currentRegionID == regionID { buffer.WriteRune('\n') } } return escapePattern.ReplaceAllString(buffer.String(), `[$1$2]`) }
[ "func", "(", "t", "*", "TextView", ")", "GetRegionText", "(", "regionID", "string", ")", "string", "{", "if", "!", "t", ".", "regions", "||", "regionID", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n\n", "var", "(", "buffer", "bytes", ".", "Buffer", "\n", "currentRegionID", "string", "\n", ")", "\n\n", "for", "_", ",", "str", ":=", "range", "t", ".", "buffer", "{", "// Find all color tags in this line.", "var", "colorTagIndices", "[", "]", "[", "]", "int", "\n", "if", "t", ".", "dynamicColors", "{", "colorTagIndices", "=", "colorPattern", ".", "FindAllStringIndex", "(", "str", ",", "-", "1", ")", "\n", "}", "\n\n", "// Find all regions in this line.", "var", "(", "regionIndices", "[", "]", "[", "]", "int", "\n", "regions", "[", "]", "[", "]", "string", "\n", ")", "\n", "if", "t", ".", "regions", "{", "regionIndices", "=", "regionPattern", ".", "FindAllStringIndex", "(", "str", ",", "-", "1", ")", "\n", "regions", "=", "regionPattern", ".", "FindAllStringSubmatch", "(", "str", ",", "-", "1", ")", "\n", "}", "\n\n", "// Analyze this line.", "var", "currentTag", ",", "currentRegion", "int", "\n", "for", "pos", ",", "ch", ":=", "range", "str", "{", "// Skip any color tags.", "if", "currentTag", "<", "len", "(", "colorTagIndices", ")", "&&", "pos", ">=", "colorTagIndices", "[", "currentTag", "]", "[", "0", "]", "&&", "pos", "<", "colorTagIndices", "[", "currentTag", "]", "[", "1", "]", "{", "if", "pos", "==", "colorTagIndices", "[", "currentTag", "]", "[", "1", "]", "-", "1", "{", "currentTag", "++", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// Skip any regions.", "if", "currentRegion", "<", "len", "(", "regionIndices", ")", "&&", "pos", ">=", "regionIndices", "[", "currentRegion", "]", "[", "0", "]", "&&", "pos", "<", "regionIndices", "[", "currentRegion", "]", "[", "1", "]", "{", "if", "pos", "==", "regionIndices", "[", "currentRegion", "]", "[", "1", "]", "-", "1", "{", "if", "currentRegionID", "==", "regionID", "{", "// This is the end of the requested region. We're done.", "return", "buffer", ".", "String", "(", ")", "\n", "}", "\n", "currentRegionID", "=", "regions", "[", "currentRegion", "]", "[", "1", "]", "\n", "currentRegion", "++", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// Add this rune.", "if", "currentRegionID", "==", "regionID", "{", "buffer", ".", "WriteRune", "(", "ch", ")", "\n", "}", "\n", "}", "\n\n", "// Add newline.", "if", "currentRegionID", "==", "regionID", "{", "buffer", ".", "WriteRune", "(", "'\\n'", ")", "\n", "}", "\n", "}", "\n\n", "return", "escapePattern", ".", "ReplaceAllString", "(", "buffer", ".", "String", "(", ")", ",", "`[$1$2]`", ")", "\n", "}" ]
// GetRegionText returns the text of the region with the given ID. If dynamic // colors are enabled, color tags are stripped from the text. Newlines are // always returned as '\n' runes. // // If the region does not exist or if regions are turned off, an empty string // is returned.
[ "GetRegionText", "returns", "the", "text", "of", "the", "region", "with", "the", "given", "ID", ".", "If", "dynamic", "colors", "are", "enabled", "color", "tags", "are", "stripped", "from", "the", "text", ".", "Newlines", "are", "always", "returned", "as", "\\", "n", "runes", ".", "If", "the", "region", "does", "not", "exist", "or", "if", "regions", "are", "turned", "off", "an", "empty", "string", "is", "returned", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L425-L489
train
rivo/tview
textview.go
Write
func (t *TextView) Write(p []byte) (n int, err error) { // Notify at the end. t.Lock() changed := t.changed t.Unlock() if changed != nil { defer changed() // Deadlocks may occur if we lock here. } t.Lock() defer t.Unlock() // Copy data over. newBytes := append(t.recentBytes, p...) t.recentBytes = nil // If we have a trailing invalid UTF-8 byte, we'll wait. if r, _ := utf8.DecodeLastRune(p); r == utf8.RuneError { t.recentBytes = newBytes return len(p), nil } // If we have a trailing open dynamic color, exclude it. if t.dynamicColors { location := openColorRegex.FindIndex(newBytes) if location != nil { t.recentBytes = newBytes[location[0]:] newBytes = newBytes[:location[0]] } } // If we have a trailing open region, exclude it. if t.regions { location := openRegionRegex.FindIndex(newBytes) if location != nil { t.recentBytes = newBytes[location[0]:] newBytes = newBytes[:location[0]] } } // Transform the new bytes into strings. newBytes = bytes.Replace(newBytes, []byte{'\t'}, bytes.Repeat([]byte{' '}, TabSize), -1) for index, line := range newLineRegex.Split(string(newBytes), -1) { if index == 0 { if len(t.buffer) == 0 { t.buffer = []string{line} } else { t.buffer[len(t.buffer)-1] += line } } else { t.buffer = append(t.buffer, line) } } // Reset the index. t.index = nil return len(p), nil }
go
func (t *TextView) Write(p []byte) (n int, err error) { // Notify at the end. t.Lock() changed := t.changed t.Unlock() if changed != nil { defer changed() // Deadlocks may occur if we lock here. } t.Lock() defer t.Unlock() // Copy data over. newBytes := append(t.recentBytes, p...) t.recentBytes = nil // If we have a trailing invalid UTF-8 byte, we'll wait. if r, _ := utf8.DecodeLastRune(p); r == utf8.RuneError { t.recentBytes = newBytes return len(p), nil } // If we have a trailing open dynamic color, exclude it. if t.dynamicColors { location := openColorRegex.FindIndex(newBytes) if location != nil { t.recentBytes = newBytes[location[0]:] newBytes = newBytes[:location[0]] } } // If we have a trailing open region, exclude it. if t.regions { location := openRegionRegex.FindIndex(newBytes) if location != nil { t.recentBytes = newBytes[location[0]:] newBytes = newBytes[:location[0]] } } // Transform the new bytes into strings. newBytes = bytes.Replace(newBytes, []byte{'\t'}, bytes.Repeat([]byte{' '}, TabSize), -1) for index, line := range newLineRegex.Split(string(newBytes), -1) { if index == 0 { if len(t.buffer) == 0 { t.buffer = []string{line} } else { t.buffer[len(t.buffer)-1] += line } } else { t.buffer = append(t.buffer, line) } } // Reset the index. t.index = nil return len(p), nil }
[ "func", "(", "t", "*", "TextView", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "// Notify at the end.", "t", ".", "Lock", "(", ")", "\n", "changed", ":=", "t", ".", "changed", "\n", "t", ".", "Unlock", "(", ")", "\n", "if", "changed", "!=", "nil", "{", "defer", "changed", "(", ")", "// Deadlocks may occur if we lock here.", "\n", "}", "\n\n", "t", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "Unlock", "(", ")", "\n\n", "// Copy data over.", "newBytes", ":=", "append", "(", "t", ".", "recentBytes", ",", "p", "...", ")", "\n", "t", ".", "recentBytes", "=", "nil", "\n\n", "// If we have a trailing invalid UTF-8 byte, we'll wait.", "if", "r", ",", "_", ":=", "utf8", ".", "DecodeLastRune", "(", "p", ")", ";", "r", "==", "utf8", ".", "RuneError", "{", "t", ".", "recentBytes", "=", "newBytes", "\n", "return", "len", "(", "p", ")", ",", "nil", "\n", "}", "\n\n", "// If we have a trailing open dynamic color, exclude it.", "if", "t", ".", "dynamicColors", "{", "location", ":=", "openColorRegex", ".", "FindIndex", "(", "newBytes", ")", "\n", "if", "location", "!=", "nil", "{", "t", ".", "recentBytes", "=", "newBytes", "[", "location", "[", "0", "]", ":", "]", "\n", "newBytes", "=", "newBytes", "[", ":", "location", "[", "0", "]", "]", "\n", "}", "\n", "}", "\n\n", "// If we have a trailing open region, exclude it.", "if", "t", ".", "regions", "{", "location", ":=", "openRegionRegex", ".", "FindIndex", "(", "newBytes", ")", "\n", "if", "location", "!=", "nil", "{", "t", ".", "recentBytes", "=", "newBytes", "[", "location", "[", "0", "]", ":", "]", "\n", "newBytes", "=", "newBytes", "[", ":", "location", "[", "0", "]", "]", "\n", "}", "\n", "}", "\n\n", "// Transform the new bytes into strings.", "newBytes", "=", "bytes", ".", "Replace", "(", "newBytes", ",", "[", "]", "byte", "{", "'\\t'", "}", ",", "bytes", ".", "Repeat", "(", "[", "]", "byte", "{", "' '", "}", ",", "TabSize", ")", ",", "-", "1", ")", "\n", "for", "index", ",", "line", ":=", "range", "newLineRegex", ".", "Split", "(", "string", "(", "newBytes", ")", ",", "-", "1", ")", "{", "if", "index", "==", "0", "{", "if", "len", "(", "t", ".", "buffer", ")", "==", "0", "{", "t", ".", "buffer", "=", "[", "]", "string", "{", "line", "}", "\n", "}", "else", "{", "t", ".", "buffer", "[", "len", "(", "t", ".", "buffer", ")", "-", "1", "]", "+=", "line", "\n", "}", "\n", "}", "else", "{", "t", ".", "buffer", "=", "append", "(", "t", ".", "buffer", ",", "line", ")", "\n", "}", "\n", "}", "\n\n", "// Reset the index.", "t", ".", "index", "=", "nil", "\n\n", "return", "len", "(", "p", ")", ",", "nil", "\n", "}" ]
// Write lets us implement the io.Writer interface. Tab characters will be // replaced with TabSize space characters. A "\n" or "\r\n" will be interpreted // as a new line.
[ "Write", "lets", "us", "implement", "the", "io", ".", "Writer", "interface", ".", "Tab", "characters", "will", "be", "replaced", "with", "TabSize", "space", "characters", ".", "A", "\\", "n", "or", "\\", "r", "\\", "n", "will", "be", "interpreted", "as", "a", "new", "line", "." ]
90b4da1bd64ceee13d2e7d782b315b819190f7bf
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/textview.go#L511-L569
train
PuerkitoBio/goquery
manipulation.go
SetHtml
func (s *Selection) SetHtml(html string) *Selection { return setHtmlNodes(s, parseHtml(html)...) }
go
func (s *Selection) SetHtml(html string) *Selection { return setHtmlNodes(s, parseHtml(html)...) }
[ "func", "(", "s", "*", "Selection", ")", "SetHtml", "(", "html", "string", ")", "*", "Selection", "{", "return", "setHtmlNodes", "(", "s", ",", "parseHtml", "(", "html", ")", "...", ")", "\n", "}" ]
// SetHtml sets the html content of each element in the selection to // specified html string.
[ "SetHtml", "sets", "the", "html", "content", "of", "each", "element", "in", "the", "selection", "to", "specified", "html", "string", "." ]
3dcf72e6c17f694381a21592651ca1464ded0e10
https://github.com/PuerkitoBio/goquery/blob/3dcf72e6c17f694381a21592651ca1464ded0e10/manipulation.go#L275-L277
train
PuerkitoBio/goquery
manipulation.go
SetText
func (s *Selection) SetText(text string) *Selection { return s.SetHtml(html.EscapeString(text)) }
go
func (s *Selection) SetText(text string) *Selection { return s.SetHtml(html.EscapeString(text)) }
[ "func", "(", "s", "*", "Selection", ")", "SetText", "(", "text", "string", ")", "*", "Selection", "{", "return", "s", ".", "SetHtml", "(", "html", ".", "EscapeString", "(", "text", ")", ")", "\n", "}" ]
// SetText sets the content of each element in the selection to specified content. // The provided text string is escaped.
[ "SetText", "sets", "the", "content", "of", "each", "element", "in", "the", "selection", "to", "specified", "content", ".", "The", "provided", "text", "string", "is", "escaped", "." ]
3dcf72e6c17f694381a21592651ca1464ded0e10
https://github.com/PuerkitoBio/goquery/blob/3dcf72e6c17f694381a21592651ca1464ded0e10/manipulation.go#L281-L283
train
PuerkitoBio/goquery
expand.go
AddBackFiltered
func (s *Selection) AddBackFiltered(selector string) *Selection { return s.AddSelection(s.prevSel.Filter(selector)) }
go
func (s *Selection) AddBackFiltered(selector string) *Selection { return s.AddSelection(s.prevSel.Filter(selector)) }
[ "func", "(", "s", "*", "Selection", ")", "AddBackFiltered", "(", "selector", "string", ")", "*", "Selection", "{", "return", "s", ".", "AddSelection", "(", "s", ".", "prevSel", ".", "Filter", "(", "selector", ")", ")", "\n", "}" ]
// AddBackFiltered reduces the previous set of elements on the stack to those that // match the selector string, and adds them to the current set. // It returns a new Selection object containing the current Selection combined // with the filtered previous one
[ "AddBackFiltered", "reduces", "the", "previous", "set", "of", "elements", "on", "the", "stack", "to", "those", "that", "match", "the", "selector", "string", "and", "adds", "them", "to", "the", "current", "set", ".", "It", "returns", "a", "new", "Selection", "object", "containing", "the", "current", "Selection", "combined", "with", "the", "filtered", "previous", "one" ]
3dcf72e6c17f694381a21592651ca1464ded0e10
https://github.com/PuerkitoBio/goquery/blob/3dcf72e6c17f694381a21592651ca1464ded0e10/expand.go#L60-L62
train
PuerkitoBio/goquery
expand.go
AddBackMatcher
func (s *Selection) AddBackMatcher(m Matcher) *Selection { return s.AddSelection(s.prevSel.FilterMatcher(m)) }
go
func (s *Selection) AddBackMatcher(m Matcher) *Selection { return s.AddSelection(s.prevSel.FilterMatcher(m)) }
[ "func", "(", "s", "*", "Selection", ")", "AddBackMatcher", "(", "m", "Matcher", ")", "*", "Selection", "{", "return", "s", ".", "AddSelection", "(", "s", ".", "prevSel", ".", "FilterMatcher", "(", "m", ")", ")", "\n", "}" ]
// AddBackMatcher reduces the previous set of elements on the stack to those that match // the mateher, and adds them to the curernt set. // It returns a new Selection object containing the current Selection combined // with the filtered previous one
[ "AddBackMatcher", "reduces", "the", "previous", "set", "of", "elements", "on", "the", "stack", "to", "those", "that", "match", "the", "mateher", "and", "adds", "them", "to", "the", "curernt", "set", ".", "It", "returns", "a", "new", "Selection", "object", "containing", "the", "current", "Selection", "combined", "with", "the", "filtered", "previous", "one" ]
3dcf72e6c17f694381a21592651ca1464ded0e10
https://github.com/PuerkitoBio/goquery/blob/3dcf72e6c17f694381a21592651ca1464ded0e10/expand.go#L68-L70
train
brocaar/loraserver
internal/maccommand/dev_status.go
RequestDevStatus
func RequestDevStatus(ds *storage.DeviceSession) storage.MACCommandBlock { block := storage.MACCommandBlock{ CID: lorawan.DevStatusReq, MACCommands: []lorawan.MACCommand{ { CID: lorawan.DevStatusReq, }, }, } ds.LastDevStatusRequested = time.Now() log.WithFields(log.Fields{ "dev_eui": ds.DevEUI, }).Info("requesting device-status") return block }
go
func RequestDevStatus(ds *storage.DeviceSession) storage.MACCommandBlock { block := storage.MACCommandBlock{ CID: lorawan.DevStatusReq, MACCommands: []lorawan.MACCommand{ { CID: lorawan.DevStatusReq, }, }, } ds.LastDevStatusRequested = time.Now() log.WithFields(log.Fields{ "dev_eui": ds.DevEUI, }).Info("requesting device-status") return block }
[ "func", "RequestDevStatus", "(", "ds", "*", "storage", ".", "DeviceSession", ")", "storage", ".", "MACCommandBlock", "{", "block", ":=", "storage", ".", "MACCommandBlock", "{", "CID", ":", "lorawan", ".", "DevStatusReq", ",", "MACCommands", ":", "[", "]", "lorawan", ".", "MACCommand", "{", "{", "CID", ":", "lorawan", ".", "DevStatusReq", ",", "}", ",", "}", ",", "}", "\n", "ds", ".", "LastDevStatusRequested", "=", "time", ".", "Now", "(", ")", "\n", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "ds", ".", "DevEUI", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "block", "\n", "}" ]
// RequestDevStatus returns a mac-command block for requesting the device-status.
[ "RequestDevStatus", "returns", "a", "mac", "-", "command", "block", "for", "requesting", "the", "device", "-", "status", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/maccommand/dev_status.go#L16-L30
train
brocaar/loraserver
internal/storage/service_profile.go
CreateServiceProfileCache
func CreateServiceProfileCache(p *redis.Pool, sp ServiceProfile) error { var buf bytes.Buffer if err := gob.NewEncoder(&buf).Encode(sp); err != nil { return errors.Wrap(err, "gob encode service-profile error") } c := p.Get() defer c.Close() key := fmt.Sprintf(ServiceProfileKeyTempl, sp.ID) exp := int64(deviceSessionTTL) / int64(time.Millisecond) _, err := c.Do("PSETEX", key, exp, buf.Bytes()) if err != nil { return errors.Wrap(err, "set service-profile error") } return nil }
go
func CreateServiceProfileCache(p *redis.Pool, sp ServiceProfile) error { var buf bytes.Buffer if err := gob.NewEncoder(&buf).Encode(sp); err != nil { return errors.Wrap(err, "gob encode service-profile error") } c := p.Get() defer c.Close() key := fmt.Sprintf(ServiceProfileKeyTempl, sp.ID) exp := int64(deviceSessionTTL) / int64(time.Millisecond) _, err := c.Do("PSETEX", key, exp, buf.Bytes()) if err != nil { return errors.Wrap(err, "set service-profile error") } return nil }
[ "func", "CreateServiceProfileCache", "(", "p", "*", "redis", ".", "Pool", ",", "sp", "ServiceProfile", ")", "error", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "gob", ".", "NewEncoder", "(", "&", "buf", ")", ".", "Encode", "(", "sp", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "c", ":=", "p", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n\n", "key", ":=", "fmt", ".", "Sprintf", "(", "ServiceProfileKeyTempl", ",", "sp", ".", "ID", ")", "\n", "exp", ":=", "int64", "(", "deviceSessionTTL", ")", "/", "int64", "(", "time", ".", "Millisecond", ")", "\n\n", "_", ",", "err", ":=", "c", ".", "Do", "(", "\"", "\"", ",", "key", ",", "exp", ",", "buf", ".", "Bytes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CreateServiceProfileCache caches the given service-profile into the Redis. // This is used for faster lookups, but also in case of roaming where we // only want to store the service-profile of a roaming device for a finite // duration. // The TTL of the service-profile is the same as that of the device-sessions.
[ "CreateServiceProfileCache", "caches", "the", "given", "service", "-", "profile", "into", "the", "Redis", ".", "This", "is", "used", "for", "faster", "lookups", "but", "also", "in", "case", "of", "roaming", "where", "we", "only", "want", "to", "store", "the", "service", "-", "profile", "of", "a", "roaming", "device", "for", "a", "finite", "duration", ".", "The", "TTL", "of", "the", "service", "-", "profile", "is", "the", "same", "as", "that", "of", "the", "device", "-", "sessions", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/service_profile.go#L136-L154
train
brocaar/loraserver
internal/storage/service_profile.go
GetServiceProfileCache
func GetServiceProfileCache(p *redis.Pool, id uuid.UUID) (ServiceProfile, error) { var sp ServiceProfile key := fmt.Sprintf(ServiceProfileKeyTempl, id) c := p.Get() defer c.Close() val, err := redis.Bytes(c.Do("GET", key)) if err != nil { if err == redis.ErrNil { return sp, ErrDoesNotExist } return sp, errors.Wrap(err, "get error") } err = gob.NewDecoder(bytes.NewReader(val)).Decode(&sp) if err != nil { return sp, errors.Wrap(err, "gob decode error") } return sp, nil }
go
func GetServiceProfileCache(p *redis.Pool, id uuid.UUID) (ServiceProfile, error) { var sp ServiceProfile key := fmt.Sprintf(ServiceProfileKeyTempl, id) c := p.Get() defer c.Close() val, err := redis.Bytes(c.Do("GET", key)) if err != nil { if err == redis.ErrNil { return sp, ErrDoesNotExist } return sp, errors.Wrap(err, "get error") } err = gob.NewDecoder(bytes.NewReader(val)).Decode(&sp) if err != nil { return sp, errors.Wrap(err, "gob decode error") } return sp, nil }
[ "func", "GetServiceProfileCache", "(", "p", "*", "redis", ".", "Pool", ",", "id", "uuid", ".", "UUID", ")", "(", "ServiceProfile", ",", "error", ")", "{", "var", "sp", "ServiceProfile", "\n", "key", ":=", "fmt", ".", "Sprintf", "(", "ServiceProfileKeyTempl", ",", "id", ")", "\n\n", "c", ":=", "p", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n\n", "val", ",", "err", ":=", "redis", ".", "Bytes", "(", "c", ".", "Do", "(", "\"", "\"", ",", "key", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "redis", ".", "ErrNil", "{", "return", "sp", ",", "ErrDoesNotExist", "\n", "}", "\n", "return", "sp", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "err", "=", "gob", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "val", ")", ")", ".", "Decode", "(", "&", "sp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "sp", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "sp", ",", "nil", "\n", "}" ]
// GetServiceProfileCache returns a cached service-profile.
[ "GetServiceProfileCache", "returns", "a", "cached", "service", "-", "profile", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/service_profile.go#L157-L178
train
brocaar/loraserver
internal/storage/service_profile.go
FlushServiceProfileCache
func FlushServiceProfileCache(p *redis.Pool, id uuid.UUID) error { key := fmt.Sprintf(ServiceProfileKeyTempl, id) c := p.Get() defer c.Close() _, err := c.Do("DEL", key) if err != nil { return errors.Wrap(err, "delete error") } return nil }
go
func FlushServiceProfileCache(p *redis.Pool, id uuid.UUID) error { key := fmt.Sprintf(ServiceProfileKeyTempl, id) c := p.Get() defer c.Close() _, err := c.Do("DEL", key) if err != nil { return errors.Wrap(err, "delete error") } return nil }
[ "func", "FlushServiceProfileCache", "(", "p", "*", "redis", ".", "Pool", ",", "id", "uuid", ".", "UUID", ")", "error", "{", "key", ":=", "fmt", ".", "Sprintf", "(", "ServiceProfileKeyTempl", ",", "id", ")", "\n", "c", ":=", "p", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n\n", "_", ",", "err", ":=", "c", ".", "Do", "(", "\"", "\"", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FlushServiceProfileCache deletes a cached service-profile.
[ "FlushServiceProfileCache", "deletes", "a", "cached", "service", "-", "profile", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/service_profile.go#L181-L191
train
brocaar/loraserver
internal/storage/service_profile.go
GetAndCacheServiceProfile
func GetAndCacheServiceProfile(db sqlx.Queryer, p *redis.Pool, id uuid.UUID) (ServiceProfile, error) { sp, err := GetServiceProfileCache(p, id) if err == nil { return sp, nil } if err != ErrDoesNotExist { log.WithFields(log.Fields{ "id": id, }).WithError(err).Error("get service-profile cache error") // we don't return as we can fall-back onto db retrieval } sp, err = GetServiceProfile(db, id) if err != nil { return ServiceProfile{}, errors.Wrap(err, "get service-profile-error") } err = CreateServiceProfileCache(p, sp) if err != nil { log.WithFields(log.Fields{ "id": id, }).WithError(err).Error("create service-profile cache error") } return sp, nil }
go
func GetAndCacheServiceProfile(db sqlx.Queryer, p *redis.Pool, id uuid.UUID) (ServiceProfile, error) { sp, err := GetServiceProfileCache(p, id) if err == nil { return sp, nil } if err != ErrDoesNotExist { log.WithFields(log.Fields{ "id": id, }).WithError(err).Error("get service-profile cache error") // we don't return as we can fall-back onto db retrieval } sp, err = GetServiceProfile(db, id) if err != nil { return ServiceProfile{}, errors.Wrap(err, "get service-profile-error") } err = CreateServiceProfileCache(p, sp) if err != nil { log.WithFields(log.Fields{ "id": id, }).WithError(err).Error("create service-profile cache error") } return sp, nil }
[ "func", "GetAndCacheServiceProfile", "(", "db", "sqlx", ".", "Queryer", ",", "p", "*", "redis", ".", "Pool", ",", "id", "uuid", ".", "UUID", ")", "(", "ServiceProfile", ",", "error", ")", "{", "sp", ",", "err", ":=", "GetServiceProfileCache", "(", "p", ",", "id", ")", "\n", "if", "err", "==", "nil", "{", "return", "sp", ",", "nil", "\n", "}", "\n\n", "if", "err", "!=", "ErrDoesNotExist", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "id", ",", "}", ")", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "// we don't return as we can fall-back onto db retrieval", "}", "\n\n", "sp", ",", "err", "=", "GetServiceProfile", "(", "db", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ServiceProfile", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "err", "=", "CreateServiceProfileCache", "(", "p", ",", "sp", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "id", ",", "}", ")", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "sp", ",", "nil", "\n", "}" ]
// GetAndCacheServiceProfile returns the service-profile from cache in case // available, else it will be retrieved from the database and then stored // in cache.
[ "GetAndCacheServiceProfile", "returns", "the", "service", "-", "profile", "from", "cache", "in", "case", "available", "else", "it", "will", "be", "retrieved", "from", "the", "database", "and", "then", "stored", "in", "cache", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/service_profile.go#L196-L222
train
brocaar/loraserver
internal/storage/service_profile.go
UpdateServiceProfile
func UpdateServiceProfile(db sqlx.Execer, sp *ServiceProfile) error { sp.UpdatedAt = time.Now() res, err := db.Exec(` update service_profile set updated_at = $2, ul_rate = $3, ul_bucket_size = $4, ul_rate_policy = $5, dl_rate = $6, dl_bucket_size = $7, dl_rate_policy = $8, add_gw_metadata = $9, dev_status_req_freq = $10, report_dev_status_battery = $11, report_dev_status_margin = $12, dr_min = $13, dr_max = $14, channel_mask = $15, pr_allowed = $16, hr_allowed = $17, ra_allowed = $18, nwk_geo_loc = $19, target_per = $20, min_gw_diversity = $21 where service_profile_id = $1`, sp.ID, sp.UpdatedAt, sp.ULRate, sp.ULBucketSize, sp.ULRatePolicy, sp.DLRate, sp.DLBucketSize, sp.DLRatePolicy, sp.AddGWMetadata, sp.DevStatusReqFreq, sp.ReportDevStatusBattery, sp.ReportDevStatusMargin, sp.DRMin, sp.DRMax, sp.ChannelMask, sp.PRAllowed, sp.HRAllowed, sp.RAAllowed, sp.NwkGeoLoc, sp.TargetPER, sp.MinGWDiversity, ) if err != nil { return handlePSQLError(err, "update error") } ra, err := res.RowsAffected() if err != nil { return handlePSQLError(err, "get rows affected error") } if ra == 0 { return ErrDoesNotExist } log.WithField("id", sp.ID).Info("service-profile updated") return nil }
go
func UpdateServiceProfile(db sqlx.Execer, sp *ServiceProfile) error { sp.UpdatedAt = time.Now() res, err := db.Exec(` update service_profile set updated_at = $2, ul_rate = $3, ul_bucket_size = $4, ul_rate_policy = $5, dl_rate = $6, dl_bucket_size = $7, dl_rate_policy = $8, add_gw_metadata = $9, dev_status_req_freq = $10, report_dev_status_battery = $11, report_dev_status_margin = $12, dr_min = $13, dr_max = $14, channel_mask = $15, pr_allowed = $16, hr_allowed = $17, ra_allowed = $18, nwk_geo_loc = $19, target_per = $20, min_gw_diversity = $21 where service_profile_id = $1`, sp.ID, sp.UpdatedAt, sp.ULRate, sp.ULBucketSize, sp.ULRatePolicy, sp.DLRate, sp.DLBucketSize, sp.DLRatePolicy, sp.AddGWMetadata, sp.DevStatusReqFreq, sp.ReportDevStatusBattery, sp.ReportDevStatusMargin, sp.DRMin, sp.DRMax, sp.ChannelMask, sp.PRAllowed, sp.HRAllowed, sp.RAAllowed, sp.NwkGeoLoc, sp.TargetPER, sp.MinGWDiversity, ) if err != nil { return handlePSQLError(err, "update error") } ra, err := res.RowsAffected() if err != nil { return handlePSQLError(err, "get rows affected error") } if ra == 0 { return ErrDoesNotExist } log.WithField("id", sp.ID).Info("service-profile updated") return nil }
[ "func", "UpdateServiceProfile", "(", "db", "sqlx", ".", "Execer", ",", "sp", "*", "ServiceProfile", ")", "error", "{", "sp", ".", "UpdatedAt", "=", "time", ".", "Now", "(", ")", "\n\n", "res", ",", "err", ":=", "db", ".", "Exec", "(", "`\n\t\tupdate service_profile set\n\t\t\tupdated_at = $2,\n\n\t\t\tul_rate = $3,\n\t\t\tul_bucket_size = $4,\n\t\t\tul_rate_policy = $5,\n\t\t\tdl_rate = $6,\n\t\t\tdl_bucket_size = $7,\n\t\t\tdl_rate_policy = $8,\n\t\t\tadd_gw_metadata = $9,\n\t\t\tdev_status_req_freq = $10,\n\t\t\treport_dev_status_battery = $11,\n\t\t\treport_dev_status_margin = $12,\n\t\t\tdr_min = $13,\n\t\t\tdr_max = $14,\n\t\t\tchannel_mask = $15,\n\t\t\tpr_allowed = $16,\n\t\t\thr_allowed = $17,\n\t\t\tra_allowed = $18,\n\t\t\tnwk_geo_loc = $19,\n\t\t\ttarget_per = $20,\n\t\t\tmin_gw_diversity = $21\n\t\twhere\n\t\t\tservice_profile_id = $1`", ",", "sp", ".", "ID", ",", "sp", ".", "UpdatedAt", ",", "sp", ".", "ULRate", ",", "sp", ".", "ULBucketSize", ",", "sp", ".", "ULRatePolicy", ",", "sp", ".", "DLRate", ",", "sp", ".", "DLBucketSize", ",", "sp", ".", "DLRatePolicy", ",", "sp", ".", "AddGWMetadata", ",", "sp", ".", "DevStatusReqFreq", ",", "sp", ".", "ReportDevStatusBattery", ",", "sp", ".", "ReportDevStatusMargin", ",", "sp", ".", "DRMin", ",", "sp", ".", "DRMax", ",", "sp", ".", "ChannelMask", ",", "sp", ".", "PRAllowed", ",", "sp", ".", "HRAllowed", ",", "sp", ".", "RAAllowed", ",", "sp", ".", "NwkGeoLoc", ",", "sp", ".", "TargetPER", ",", "sp", ".", "MinGWDiversity", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "handlePSQLError", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "ra", ",", "err", ":=", "res", ".", "RowsAffected", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "handlePSQLError", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "ra", "==", "0", "{", "return", "ErrDoesNotExist", "\n", "}", "\n\n", "log", ".", "WithField", "(", "\"", "\"", ",", "sp", ".", "ID", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// UpdateServiceProfile updates the given service-profile.
[ "UpdateServiceProfile", "updates", "the", "given", "service", "-", "profile", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/service_profile.go#L236-L299
train
brocaar/loraserver
internal/storage/db.go
Beginx
func (db *DBLogger) Beginx() (*TxLogger, error) { tx, err := db.DB.Beginx() return &TxLogger{tx}, err }
go
func (db *DBLogger) Beginx() (*TxLogger, error) { tx, err := db.DB.Beginx() return &TxLogger{tx}, err }
[ "func", "(", "db", "*", "DBLogger", ")", "Beginx", "(", ")", "(", "*", "TxLogger", ",", "error", ")", "{", "tx", ",", "err", ":=", "db", ".", "DB", ".", "Beginx", "(", ")", "\n", "return", "&", "TxLogger", "{", "tx", "}", ",", "err", "\n", "}" ]
// Beginx returns a transaction with logging.
[ "Beginx", "returns", "a", "transaction", "with", "logging", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/db.go#L34-L37
train
brocaar/loraserver
internal/maccommand/rx_timing_setup.go
RequestRXTimingSetup
func RequestRXTimingSetup(del int) storage.MACCommandBlock { return storage.MACCommandBlock{ CID: lorawan.RXTimingSetupReq, MACCommands: []lorawan.MACCommand{ { CID: lorawan.RXTimingSetupReq, Payload: &lorawan.RXTimingSetupReqPayload{ Delay: uint8(del), }, }, }, } }
go
func RequestRXTimingSetup(del int) storage.MACCommandBlock { return storage.MACCommandBlock{ CID: lorawan.RXTimingSetupReq, MACCommands: []lorawan.MACCommand{ { CID: lorawan.RXTimingSetupReq, Payload: &lorawan.RXTimingSetupReqPayload{ Delay: uint8(del), }, }, }, } }
[ "func", "RequestRXTimingSetup", "(", "del", "int", ")", "storage", ".", "MACCommandBlock", "{", "return", "storage", ".", "MACCommandBlock", "{", "CID", ":", "lorawan", ".", "RXTimingSetupReq", ",", "MACCommands", ":", "[", "]", "lorawan", ".", "MACCommand", "{", "{", "CID", ":", "lorawan", ".", "RXTimingSetupReq", ",", "Payload", ":", "&", "lorawan", ".", "RXTimingSetupReqPayload", "{", "Delay", ":", "uint8", "(", "del", ")", ",", "}", ",", "}", ",", "}", ",", "}", "\n", "}" ]
// RequestRXTimingSetup modifies the RX delay between the end of the TX // and the opening of the first reception slot.
[ "RequestRXTimingSetup", "modifies", "the", "RX", "delay", "between", "the", "end", "of", "the", "TX", "and", "the", "opening", "of", "the", "first", "reception", "slot", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/maccommand/rx_timing_setup.go#L13-L25
train
brocaar/loraserver
internal/api/network_server.go
DeleteRoutingProfile
func (n *NetworkServerAPI) DeleteRoutingProfile(ctx context.Context, req *ns.DeleteRoutingProfileRequest) (*empty.Empty, error) { var rpID uuid.UUID copy(rpID[:], req.Id) if err := storage.DeleteRoutingProfile(storage.DB(), rpID); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) DeleteRoutingProfile(ctx context.Context, req *ns.DeleteRoutingProfileRequest) (*empty.Empty, error) { var rpID uuid.UUID copy(rpID[:], req.Id) if err := storage.DeleteRoutingProfile(storage.DB(), rpID); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "DeleteRoutingProfile", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "DeleteRoutingProfileRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "var", "rpID", "uuid", ".", "UUID", "\n", "copy", "(", "rpID", "[", ":", "]", ",", "req", ".", "Id", ")", "\n\n", "if", "err", ":=", "storage", ".", "DeleteRoutingProfile", "(", "storage", ".", "DB", "(", ")", ",", "rpID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// DeleteRoutingProfile deletes the routing-profile matching the given id.
[ "DeleteRoutingProfile", "deletes", "the", "routing", "-", "profile", "matching", "the", "given", "id", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L322-L331
train
brocaar/loraserver
internal/api/network_server.go
CreateDeviceProfile
func (n *NetworkServerAPI) CreateDeviceProfile(ctx context.Context, req *ns.CreateDeviceProfileRequest) (*ns.CreateDeviceProfileResponse, error) { if req.DeviceProfile == nil { return nil, grpc.Errorf(codes.InvalidArgument, "device_profile must not be nil") } var dpID uuid.UUID copy(dpID[:], req.DeviceProfile.Id) var factoryPresetFreqs []int for _, f := range req.DeviceProfile.FactoryPresetFreqs { factoryPresetFreqs = append(factoryPresetFreqs, int(f)) } dp := storage.DeviceProfile{ ID: dpID, SupportsClassB: req.DeviceProfile.SupportsClassB, ClassBTimeout: int(req.DeviceProfile.ClassBTimeout), PingSlotPeriod: int(req.DeviceProfile.PingSlotPeriod), PingSlotDR: int(req.DeviceProfile.PingSlotDr), PingSlotFreq: int(req.DeviceProfile.PingSlotFreq), SupportsClassC: req.DeviceProfile.SupportsClassC, ClassCTimeout: int(req.DeviceProfile.ClassCTimeout), MACVersion: req.DeviceProfile.MacVersion, RegParamsRevision: req.DeviceProfile.RegParamsRevision, RXDelay1: int(req.DeviceProfile.RxDelay_1), RXDROffset1: int(req.DeviceProfile.RxDrOffset_1), RXDataRate2: int(req.DeviceProfile.RxDatarate_2), RXFreq2: int(req.DeviceProfile.RxFreq_2), FactoryPresetFreqs: factoryPresetFreqs, MaxEIRP: int(req.DeviceProfile.MaxEirp), MaxDutyCycle: int(req.DeviceProfile.MaxDutyCycle), SupportsJoin: req.DeviceProfile.SupportsJoin, Supports32bitFCnt: req.DeviceProfile.Supports_32BitFCnt, RFRegion: band.Band().Name(), } if err := storage.CreateDeviceProfile(storage.DB(), &dp); err != nil { return nil, errToRPCError(err) } return &ns.CreateDeviceProfileResponse{ Id: dp.ID.Bytes(), }, nil }
go
func (n *NetworkServerAPI) CreateDeviceProfile(ctx context.Context, req *ns.CreateDeviceProfileRequest) (*ns.CreateDeviceProfileResponse, error) { if req.DeviceProfile == nil { return nil, grpc.Errorf(codes.InvalidArgument, "device_profile must not be nil") } var dpID uuid.UUID copy(dpID[:], req.DeviceProfile.Id) var factoryPresetFreqs []int for _, f := range req.DeviceProfile.FactoryPresetFreqs { factoryPresetFreqs = append(factoryPresetFreqs, int(f)) } dp := storage.DeviceProfile{ ID: dpID, SupportsClassB: req.DeviceProfile.SupportsClassB, ClassBTimeout: int(req.DeviceProfile.ClassBTimeout), PingSlotPeriod: int(req.DeviceProfile.PingSlotPeriod), PingSlotDR: int(req.DeviceProfile.PingSlotDr), PingSlotFreq: int(req.DeviceProfile.PingSlotFreq), SupportsClassC: req.DeviceProfile.SupportsClassC, ClassCTimeout: int(req.DeviceProfile.ClassCTimeout), MACVersion: req.DeviceProfile.MacVersion, RegParamsRevision: req.DeviceProfile.RegParamsRevision, RXDelay1: int(req.DeviceProfile.RxDelay_1), RXDROffset1: int(req.DeviceProfile.RxDrOffset_1), RXDataRate2: int(req.DeviceProfile.RxDatarate_2), RXFreq2: int(req.DeviceProfile.RxFreq_2), FactoryPresetFreqs: factoryPresetFreqs, MaxEIRP: int(req.DeviceProfile.MaxEirp), MaxDutyCycle: int(req.DeviceProfile.MaxDutyCycle), SupportsJoin: req.DeviceProfile.SupportsJoin, Supports32bitFCnt: req.DeviceProfile.Supports_32BitFCnt, RFRegion: band.Band().Name(), } if err := storage.CreateDeviceProfile(storage.DB(), &dp); err != nil { return nil, errToRPCError(err) } return &ns.CreateDeviceProfileResponse{ Id: dp.ID.Bytes(), }, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "CreateDeviceProfile", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "CreateDeviceProfileRequest", ")", "(", "*", "ns", ".", "CreateDeviceProfileResponse", ",", "error", ")", "{", "if", "req", ".", "DeviceProfile", "==", "nil", "{", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "dpID", "uuid", ".", "UUID", "\n", "copy", "(", "dpID", "[", ":", "]", ",", "req", ".", "DeviceProfile", ".", "Id", ")", "\n\n", "var", "factoryPresetFreqs", "[", "]", "int", "\n", "for", "_", ",", "f", ":=", "range", "req", ".", "DeviceProfile", ".", "FactoryPresetFreqs", "{", "factoryPresetFreqs", "=", "append", "(", "factoryPresetFreqs", ",", "int", "(", "f", ")", ")", "\n", "}", "\n\n", "dp", ":=", "storage", ".", "DeviceProfile", "{", "ID", ":", "dpID", ",", "SupportsClassB", ":", "req", ".", "DeviceProfile", ".", "SupportsClassB", ",", "ClassBTimeout", ":", "int", "(", "req", ".", "DeviceProfile", ".", "ClassBTimeout", ")", ",", "PingSlotPeriod", ":", "int", "(", "req", ".", "DeviceProfile", ".", "PingSlotPeriod", ")", ",", "PingSlotDR", ":", "int", "(", "req", ".", "DeviceProfile", ".", "PingSlotDr", ")", ",", "PingSlotFreq", ":", "int", "(", "req", ".", "DeviceProfile", ".", "PingSlotFreq", ")", ",", "SupportsClassC", ":", "req", ".", "DeviceProfile", ".", "SupportsClassC", ",", "ClassCTimeout", ":", "int", "(", "req", ".", "DeviceProfile", ".", "ClassCTimeout", ")", ",", "MACVersion", ":", "req", ".", "DeviceProfile", ".", "MacVersion", ",", "RegParamsRevision", ":", "req", ".", "DeviceProfile", ".", "RegParamsRevision", ",", "RXDelay1", ":", "int", "(", "req", ".", "DeviceProfile", ".", "RxDelay_1", ")", ",", "RXDROffset1", ":", "int", "(", "req", ".", "DeviceProfile", ".", "RxDrOffset_1", ")", ",", "RXDataRate2", ":", "int", "(", "req", ".", "DeviceProfile", ".", "RxDatarate_2", ")", ",", "RXFreq2", ":", "int", "(", "req", ".", "DeviceProfile", ".", "RxFreq_2", ")", ",", "FactoryPresetFreqs", ":", "factoryPresetFreqs", ",", "MaxEIRP", ":", "int", "(", "req", ".", "DeviceProfile", ".", "MaxEirp", ")", ",", "MaxDutyCycle", ":", "int", "(", "req", ".", "DeviceProfile", ".", "MaxDutyCycle", ")", ",", "SupportsJoin", ":", "req", ".", "DeviceProfile", ".", "SupportsJoin", ",", "Supports32bitFCnt", ":", "req", ".", "DeviceProfile", ".", "Supports_32BitFCnt", ",", "RFRegion", ":", "band", ".", "Band", "(", ")", ".", "Name", "(", ")", ",", "}", "\n\n", "if", "err", ":=", "storage", ".", "CreateDeviceProfile", "(", "storage", ".", "DB", "(", ")", ",", "&", "dp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "ns", ".", "CreateDeviceProfileResponse", "{", "Id", ":", "dp", ".", "ID", ".", "Bytes", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// CreateDeviceProfile creates the given device-profile. // The RFRegion field will get set automatically according to the configured band.
[ "CreateDeviceProfile", "creates", "the", "given", "device", "-", "profile", ".", "The", "RFRegion", "field", "will", "get", "set", "automatically", "according", "to", "the", "configured", "band", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L335-L378
train
brocaar/loraserver
internal/api/network_server.go
DeleteDeviceProfile
func (n *NetworkServerAPI) DeleteDeviceProfile(ctx context.Context, req *ns.DeleteDeviceProfileRequest) (*empty.Empty, error) { var dpID uuid.UUID copy(dpID[:], req.Id) if err := storage.FlushDeviceProfileCache(storage.RedisPool(), dpID); err != nil { return nil, errToRPCError(err) } if err := storage.DeleteDeviceProfile(storage.DB(), dpID); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) DeleteDeviceProfile(ctx context.Context, req *ns.DeleteDeviceProfileRequest) (*empty.Empty, error) { var dpID uuid.UUID copy(dpID[:], req.Id) if err := storage.FlushDeviceProfileCache(storage.RedisPool(), dpID); err != nil { return nil, errToRPCError(err) } if err := storage.DeleteDeviceProfile(storage.DB(), dpID); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "DeleteDeviceProfile", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "DeleteDeviceProfileRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "var", "dpID", "uuid", ".", "UUID", "\n", "copy", "(", "dpID", "[", ":", "]", ",", "req", ".", "Id", ")", "\n\n", "if", "err", ":=", "storage", ".", "FlushDeviceProfileCache", "(", "storage", ".", "RedisPool", "(", ")", ",", "dpID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "storage", ".", "DeleteDeviceProfile", "(", "storage", ".", "DB", "(", ")", ",", "dpID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// DeleteDeviceProfile deletes the device-profile matching the given id.
[ "DeleteDeviceProfile", "deletes", "the", "device", "-", "profile", "matching", "the", "given", "id", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L485-L498
train
brocaar/loraserver
internal/api/network_server.go
DeactivateDevice
func (n *NetworkServerAPI) DeactivateDevice(ctx context.Context, req *ns.DeactivateDeviceRequest) (*empty.Empty, error) { var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) if err := storage.DeleteDeviceSession(storage.RedisPool(), devEUI); err != nil { return nil, errToRPCError(err) } if err := storage.FlushDeviceQueueForDevEUI(storage.DB(), devEUI); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) DeactivateDevice(ctx context.Context, req *ns.DeactivateDeviceRequest) (*empty.Empty, error) { var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) if err := storage.DeleteDeviceSession(storage.RedisPool(), devEUI); err != nil { return nil, errToRPCError(err) } if err := storage.FlushDeviceQueueForDevEUI(storage.DB(), devEUI); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "DeactivateDevice", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "DeactivateDeviceRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "var", "devEUI", "lorawan", ".", "EUI64", "\n", "copy", "(", "devEUI", "[", ":", "]", ",", "req", ".", "DevEui", ")", "\n\n", "if", "err", ":=", "storage", ".", "DeleteDeviceSession", "(", "storage", ".", "RedisPool", "(", ")", ",", "devEUI", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "storage", ".", "FlushDeviceQueueForDevEUI", "(", "storage", ".", "DB", "(", ")", ",", "devEUI", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// DeactivateDevice de-activates a device.
[ "DeactivateDevice", "de", "-", "activates", "a", "device", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L702-L715
train
brocaar/loraserver
internal/api/network_server.go
GetDeviceActivation
func (n *NetworkServerAPI) GetDeviceActivation(ctx context.Context, req *ns.GetDeviceActivationRequest) (*ns.GetDeviceActivationResponse, error) { var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) ds, err := storage.GetDeviceSession(storage.RedisPool(), devEUI) if err != nil { return nil, errToRPCError(err) } return &ns.GetDeviceActivationResponse{ DeviceActivation: &ns.DeviceActivation{ DevEui: ds.DevEUI[:], DevAddr: ds.DevAddr[:], SNwkSIntKey: ds.SNwkSIntKey[:], FNwkSIntKey: ds.FNwkSIntKey[:], NwkSEncKey: ds.NwkSEncKey[:], FCntUp: ds.FCntUp, NFCntDown: ds.NFCntDown, AFCntDown: ds.AFCntDown, SkipFCntCheck: ds.SkipFCntValidation, }, }, nil }
go
func (n *NetworkServerAPI) GetDeviceActivation(ctx context.Context, req *ns.GetDeviceActivationRequest) (*ns.GetDeviceActivationResponse, error) { var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) ds, err := storage.GetDeviceSession(storage.RedisPool(), devEUI) if err != nil { return nil, errToRPCError(err) } return &ns.GetDeviceActivationResponse{ DeviceActivation: &ns.DeviceActivation{ DevEui: ds.DevEUI[:], DevAddr: ds.DevAddr[:], SNwkSIntKey: ds.SNwkSIntKey[:], FNwkSIntKey: ds.FNwkSIntKey[:], NwkSEncKey: ds.NwkSEncKey[:], FCntUp: ds.FCntUp, NFCntDown: ds.NFCntDown, AFCntDown: ds.AFCntDown, SkipFCntCheck: ds.SkipFCntValidation, }, }, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "GetDeviceActivation", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "GetDeviceActivationRequest", ")", "(", "*", "ns", ".", "GetDeviceActivationResponse", ",", "error", ")", "{", "var", "devEUI", "lorawan", ".", "EUI64", "\n", "copy", "(", "devEUI", "[", ":", "]", ",", "req", ".", "DevEui", ")", "\n\n", "ds", ",", "err", ":=", "storage", ".", "GetDeviceSession", "(", "storage", ".", "RedisPool", "(", ")", ",", "devEUI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "ns", ".", "GetDeviceActivationResponse", "{", "DeviceActivation", ":", "&", "ns", ".", "DeviceActivation", "{", "DevEui", ":", "ds", ".", "DevEUI", "[", ":", "]", ",", "DevAddr", ":", "ds", ".", "DevAddr", "[", ":", "]", ",", "SNwkSIntKey", ":", "ds", ".", "SNwkSIntKey", "[", ":", "]", ",", "FNwkSIntKey", ":", "ds", ".", "FNwkSIntKey", "[", ":", "]", ",", "NwkSEncKey", ":", "ds", ".", "NwkSEncKey", "[", ":", "]", ",", "FCntUp", ":", "ds", ".", "FCntUp", ",", "NFCntDown", ":", "ds", ".", "NFCntDown", ",", "AFCntDown", ":", "ds", ".", "AFCntDown", ",", "SkipFCntCheck", ":", "ds", ".", "SkipFCntValidation", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// GetDeviceActivation returns the device activation details.
[ "GetDeviceActivation", "returns", "the", "device", "activation", "details", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L718-L740
train
brocaar/loraserver
internal/api/network_server.go
GetRandomDevAddr
func (n *NetworkServerAPI) GetRandomDevAddr(ctx context.Context, req *empty.Empty) (*ns.GetRandomDevAddrResponse, error) { devAddr, err := storage.GetRandomDevAddr(storage.RedisPool(), config.C.NetworkServer.NetID) if err != nil { return nil, errToRPCError(err) } return &ns.GetRandomDevAddrResponse{ DevAddr: devAddr[:], }, nil }
go
func (n *NetworkServerAPI) GetRandomDevAddr(ctx context.Context, req *empty.Empty) (*ns.GetRandomDevAddrResponse, error) { devAddr, err := storage.GetRandomDevAddr(storage.RedisPool(), config.C.NetworkServer.NetID) if err != nil { return nil, errToRPCError(err) } return &ns.GetRandomDevAddrResponse{ DevAddr: devAddr[:], }, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "GetRandomDevAddr", "(", "ctx", "context", ".", "Context", ",", "req", "*", "empty", ".", "Empty", ")", "(", "*", "ns", ".", "GetRandomDevAddrResponse", ",", "error", ")", "{", "devAddr", ",", "err", ":=", "storage", ".", "GetRandomDevAddr", "(", "storage", ".", "RedisPool", "(", ")", ",", "config", ".", "C", ".", "NetworkServer", ".", "NetID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "ns", ".", "GetRandomDevAddrResponse", "{", "DevAddr", ":", "devAddr", "[", ":", "]", ",", "}", ",", "nil", "\n", "}" ]
// GetRandomDevAddr returns a random DevAddr.
[ "GetRandomDevAddr", "returns", "a", "random", "DevAddr", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L743-L752
train
brocaar/loraserver
internal/api/network_server.go
CreateMACCommandQueueItem
func (n *NetworkServerAPI) CreateMACCommandQueueItem(ctx context.Context, req *ns.CreateMACCommandQueueItemRequest) (*empty.Empty, error) { var commands []lorawan.MACCommand var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) for _, b := range req.Commands { var mac lorawan.MACCommand if err := mac.UnmarshalBinary(false, b); err != nil { return nil, grpc.Errorf(codes.InvalidArgument, err.Error()) } commands = append(commands, mac) } block := storage.MACCommandBlock{ CID: lorawan.CID(req.Cid), External: true, MACCommands: commands, } if err := storage.CreateMACCommandQueueItem(storage.RedisPool(), devEUI, block); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) CreateMACCommandQueueItem(ctx context.Context, req *ns.CreateMACCommandQueueItemRequest) (*empty.Empty, error) { var commands []lorawan.MACCommand var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) for _, b := range req.Commands { var mac lorawan.MACCommand if err := mac.UnmarshalBinary(false, b); err != nil { return nil, grpc.Errorf(codes.InvalidArgument, err.Error()) } commands = append(commands, mac) } block := storage.MACCommandBlock{ CID: lorawan.CID(req.Cid), External: true, MACCommands: commands, } if err := storage.CreateMACCommandQueueItem(storage.RedisPool(), devEUI, block); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "CreateMACCommandQueueItem", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "CreateMACCommandQueueItemRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "var", "commands", "[", "]", "lorawan", ".", "MACCommand", "\n", "var", "devEUI", "lorawan", ".", "EUI64", "\n\n", "copy", "(", "devEUI", "[", ":", "]", ",", "req", ".", "DevEui", ")", "\n\n", "for", "_", ",", "b", ":=", "range", "req", ".", "Commands", "{", "var", "mac", "lorawan", ".", "MACCommand", "\n", "if", "err", ":=", "mac", ".", "UnmarshalBinary", "(", "false", ",", "b", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "commands", "=", "append", "(", "commands", ",", "mac", ")", "\n", "}", "\n\n", "block", ":=", "storage", ".", "MACCommandBlock", "{", "CID", ":", "lorawan", ".", "CID", "(", "req", ".", "Cid", ")", ",", "External", ":", "true", ",", "MACCommands", ":", "commands", ",", "}", "\n\n", "if", "err", ":=", "storage", ".", "CreateMACCommandQueueItem", "(", "storage", ".", "RedisPool", "(", ")", ",", "devEUI", ",", "block", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// CreateMACCommandQueueItem adds a data down MAC command to the queue. // It replaces already enqueued mac-commands with the same CID.
[ "CreateMACCommandQueueItem", "adds", "a", "data", "down", "MAC", "command", "to", "the", "queue", ".", "It", "replaces", "already", "enqueued", "mac", "-", "commands", "with", "the", "same", "CID", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L756-L781
train
brocaar/loraserver
internal/api/network_server.go
SendProprietaryPayload
func (n *NetworkServerAPI) SendProprietaryPayload(ctx context.Context, req *ns.SendProprietaryPayloadRequest) (*empty.Empty, error) { var mic lorawan.MIC var gwIDs []lorawan.EUI64 copy(mic[:], req.Mic) for i := range req.GatewayMacs { var id lorawan.EUI64 copy(id[:], req.GatewayMacs[i]) gwIDs = append(gwIDs, id) } err := proprietarydown.Handle(req.MacPayload, mic, gwIDs, req.PolarizationInversion, int(req.Frequency), int(req.Dr)) if err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) SendProprietaryPayload(ctx context.Context, req *ns.SendProprietaryPayloadRequest) (*empty.Empty, error) { var mic lorawan.MIC var gwIDs []lorawan.EUI64 copy(mic[:], req.Mic) for i := range req.GatewayMacs { var id lorawan.EUI64 copy(id[:], req.GatewayMacs[i]) gwIDs = append(gwIDs, id) } err := proprietarydown.Handle(req.MacPayload, mic, gwIDs, req.PolarizationInversion, int(req.Frequency), int(req.Dr)) if err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "SendProprietaryPayload", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "SendProprietaryPayloadRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "var", "mic", "lorawan", ".", "MIC", "\n", "var", "gwIDs", "[", "]", "lorawan", ".", "EUI64", "\n\n", "copy", "(", "mic", "[", ":", "]", ",", "req", ".", "Mic", ")", "\n", "for", "i", ":=", "range", "req", ".", "GatewayMacs", "{", "var", "id", "lorawan", ".", "EUI64", "\n", "copy", "(", "id", "[", ":", "]", ",", "req", ".", "GatewayMacs", "[", "i", "]", ")", "\n", "gwIDs", "=", "append", "(", "gwIDs", ",", "id", ")", "\n", "}", "\n\n", "err", ":=", "proprietarydown", ".", "Handle", "(", "req", ".", "MacPayload", ",", "mic", ",", "gwIDs", ",", "req", ".", "PolarizationInversion", ",", "int", "(", "req", ".", "Frequency", ")", ",", "int", "(", "req", ".", "Dr", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// SendProprietaryPayload send a payload using the 'Proprietary' LoRaWAN message-type.
[ "SendProprietaryPayload", "send", "a", "payload", "using", "the", "Proprietary", "LoRaWAN", "message", "-", "type", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L784-L801
train
brocaar/loraserver
internal/api/network_server.go
GetGateway
func (n *NetworkServerAPI) GetGateway(ctx context.Context, req *ns.GetGatewayRequest) (*ns.GetGatewayResponse, error) { var id lorawan.EUI64 copy(id[:], req.Id) gw, err := storage.GetGateway(storage.DB(), id) if err != nil { return nil, errToRPCError(err) } resp := ns.GetGatewayResponse{ Gateway: &ns.Gateway{ Id: gw.GatewayID[:], Location: &common.Location{ Latitude: gw.Location.Latitude, Longitude: gw.Location.Longitude, Altitude: gw.Altitude, }, }, } resp.CreatedAt, _ = ptypes.TimestampProto(gw.CreatedAt) resp.UpdatedAt, _ = ptypes.TimestampProto(gw.UpdatedAt) if gw.GatewayProfileID != nil { resp.Gateway.GatewayProfileId = gw.GatewayProfileID.Bytes() } if gw.FirstSeenAt != nil { resp.FirstSeenAt, _ = ptypes.TimestampProto(*gw.FirstSeenAt) } if gw.LastSeenAt != nil { resp.LastSeenAt, _ = ptypes.TimestampProto(*gw.LastSeenAt) } for i := range gw.Boards { var gwBoard ns.GatewayBoard if gw.Boards[i].FPGAID != nil { gwBoard.FpgaId = gw.Boards[i].FPGAID[:] } if gw.Boards[i].FineTimestampKey != nil { gwBoard.FineTimestampKey = gw.Boards[i].FineTimestampKey[:] } resp.Gateway.Boards = append(resp.Gateway.Boards, &gwBoard) } return &resp, nil }
go
func (n *NetworkServerAPI) GetGateway(ctx context.Context, req *ns.GetGatewayRequest) (*ns.GetGatewayResponse, error) { var id lorawan.EUI64 copy(id[:], req.Id) gw, err := storage.GetGateway(storage.DB(), id) if err != nil { return nil, errToRPCError(err) } resp := ns.GetGatewayResponse{ Gateway: &ns.Gateway{ Id: gw.GatewayID[:], Location: &common.Location{ Latitude: gw.Location.Latitude, Longitude: gw.Location.Longitude, Altitude: gw.Altitude, }, }, } resp.CreatedAt, _ = ptypes.TimestampProto(gw.CreatedAt) resp.UpdatedAt, _ = ptypes.TimestampProto(gw.UpdatedAt) if gw.GatewayProfileID != nil { resp.Gateway.GatewayProfileId = gw.GatewayProfileID.Bytes() } if gw.FirstSeenAt != nil { resp.FirstSeenAt, _ = ptypes.TimestampProto(*gw.FirstSeenAt) } if gw.LastSeenAt != nil { resp.LastSeenAt, _ = ptypes.TimestampProto(*gw.LastSeenAt) } for i := range gw.Boards { var gwBoard ns.GatewayBoard if gw.Boards[i].FPGAID != nil { gwBoard.FpgaId = gw.Boards[i].FPGAID[:] } if gw.Boards[i].FineTimestampKey != nil { gwBoard.FineTimestampKey = gw.Boards[i].FineTimestampKey[:] } resp.Gateway.Boards = append(resp.Gateway.Boards, &gwBoard) } return &resp, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "GetGateway", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "GetGatewayRequest", ")", "(", "*", "ns", ".", "GetGatewayResponse", ",", "error", ")", "{", "var", "id", "lorawan", ".", "EUI64", "\n", "copy", "(", "id", "[", ":", "]", ",", "req", ".", "Id", ")", "\n\n", "gw", ",", "err", ":=", "storage", ".", "GetGateway", "(", "storage", ".", "DB", "(", ")", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "resp", ":=", "ns", ".", "GetGatewayResponse", "{", "Gateway", ":", "&", "ns", ".", "Gateway", "{", "Id", ":", "gw", ".", "GatewayID", "[", ":", "]", ",", "Location", ":", "&", "common", ".", "Location", "{", "Latitude", ":", "gw", ".", "Location", ".", "Latitude", ",", "Longitude", ":", "gw", ".", "Location", ".", "Longitude", ",", "Altitude", ":", "gw", ".", "Altitude", ",", "}", ",", "}", ",", "}", "\n\n", "resp", ".", "CreatedAt", ",", "_", "=", "ptypes", ".", "TimestampProto", "(", "gw", ".", "CreatedAt", ")", "\n", "resp", ".", "UpdatedAt", ",", "_", "=", "ptypes", ".", "TimestampProto", "(", "gw", ".", "UpdatedAt", ")", "\n\n", "if", "gw", ".", "GatewayProfileID", "!=", "nil", "{", "resp", ".", "Gateway", ".", "GatewayProfileId", "=", "gw", ".", "GatewayProfileID", ".", "Bytes", "(", ")", "\n", "}", "\n\n", "if", "gw", ".", "FirstSeenAt", "!=", "nil", "{", "resp", ".", "FirstSeenAt", ",", "_", "=", "ptypes", ".", "TimestampProto", "(", "*", "gw", ".", "FirstSeenAt", ")", "\n", "}", "\n\n", "if", "gw", ".", "LastSeenAt", "!=", "nil", "{", "resp", ".", "LastSeenAt", ",", "_", "=", "ptypes", ".", "TimestampProto", "(", "*", "gw", ".", "LastSeenAt", ")", "\n", "}", "\n\n", "for", "i", ":=", "range", "gw", ".", "Boards", "{", "var", "gwBoard", "ns", ".", "GatewayBoard", "\n", "if", "gw", ".", "Boards", "[", "i", "]", ".", "FPGAID", "!=", "nil", "{", "gwBoard", ".", "FpgaId", "=", "gw", ".", "Boards", "[", "i", "]", ".", "FPGAID", "[", ":", "]", "\n", "}", "\n\n", "if", "gw", ".", "Boards", "[", "i", "]", ".", "FineTimestampKey", "!=", "nil", "{", "gwBoard", ".", "FineTimestampKey", "=", "gw", ".", "Boards", "[", "i", "]", ".", "FineTimestampKey", "[", ":", "]", "\n", "}", "\n\n", "resp", ".", "Gateway", ".", "Boards", "=", "append", "(", "resp", ".", "Gateway", ".", "Boards", ",", "&", "gwBoard", ")", "\n", "}", "\n\n", "return", "&", "resp", ",", "nil", "\n", "}" ]
// GetGateway returns data for a particular gateway.
[ "GetGateway", "returns", "data", "for", "a", "particular", "gateway", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L863-L912
train
brocaar/loraserver
internal/api/network_server.go
DeleteGateway
func (n *NetworkServerAPI) DeleteGateway(ctx context.Context, req *ns.DeleteGatewayRequest) (*empty.Empty, error) { var id lorawan.EUI64 copy(id[:], req.Id) if err := storage.FlushGatewayCache(storage.RedisPool(), id); err != nil { return nil, errToRPCError(err) } if err := storage.DeleteGateway(storage.DB(), id); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) DeleteGateway(ctx context.Context, req *ns.DeleteGatewayRequest) (*empty.Empty, error) { var id lorawan.EUI64 copy(id[:], req.Id) if err := storage.FlushGatewayCache(storage.RedisPool(), id); err != nil { return nil, errToRPCError(err) } if err := storage.DeleteGateway(storage.DB(), id); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "DeleteGateway", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "DeleteGatewayRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "var", "id", "lorawan", ".", "EUI64", "\n", "copy", "(", "id", "[", ":", "]", ",", "req", ".", "Id", ")", "\n\n", "if", "err", ":=", "storage", ".", "FlushGatewayCache", "(", "storage", ".", "RedisPool", "(", ")", ",", "id", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "storage", ".", "DeleteGateway", "(", "storage", ".", "DB", "(", ")", ",", "id", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// DeleteGateway deletes a gateway.
[ "DeleteGateway", "deletes", "a", "gateway", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L984-L997
train
brocaar/loraserver
internal/api/network_server.go
GetGatewayStats
func (n *NetworkServerAPI) GetGatewayStats(ctx context.Context, req *ns.GetGatewayStatsRequest) (*ns.GetGatewayStatsResponse, error) { gatewayID := helpers.GetGatewayID(req) start, err := ptypes.Timestamp(req.StartTimestamp) if err != nil { return nil, grpc.Errorf(codes.InvalidArgument, err.Error()) } end, err := ptypes.Timestamp(req.EndTimestamp) if err != nil { return nil, grpc.Errorf(codes.InvalidArgument, err.Error()) } metrics, err := storage.GetMetrics(storage.RedisPool(), storage.AggregationInterval(req.Interval.String()), "gw:"+gatewayID.String(), start, end) if err != nil { return nil, errToRPCError(err) } var resp ns.GetGatewayStatsResponse for _, m := range metrics { row := ns.GatewayStats{ RxPacketsReceived: int32(m.Metrics["rx_count"]), RxPacketsReceivedOk: int32(m.Metrics["rx_ok_count"]), TxPacketsReceived: int32(m.Metrics["tx_count"]), TxPacketsEmitted: int32(m.Metrics["tx_ok_count"]), } row.Timestamp, err = ptypes.TimestampProto(m.Time) if err != nil { return nil, errToRPCError(err) } resp.Result = append(resp.Result, &row) } return &resp, nil }
go
func (n *NetworkServerAPI) GetGatewayStats(ctx context.Context, req *ns.GetGatewayStatsRequest) (*ns.GetGatewayStatsResponse, error) { gatewayID := helpers.GetGatewayID(req) start, err := ptypes.Timestamp(req.StartTimestamp) if err != nil { return nil, grpc.Errorf(codes.InvalidArgument, err.Error()) } end, err := ptypes.Timestamp(req.EndTimestamp) if err != nil { return nil, grpc.Errorf(codes.InvalidArgument, err.Error()) } metrics, err := storage.GetMetrics(storage.RedisPool(), storage.AggregationInterval(req.Interval.String()), "gw:"+gatewayID.String(), start, end) if err != nil { return nil, errToRPCError(err) } var resp ns.GetGatewayStatsResponse for _, m := range metrics { row := ns.GatewayStats{ RxPacketsReceived: int32(m.Metrics["rx_count"]), RxPacketsReceivedOk: int32(m.Metrics["rx_ok_count"]), TxPacketsReceived: int32(m.Metrics["tx_count"]), TxPacketsEmitted: int32(m.Metrics["tx_ok_count"]), } row.Timestamp, err = ptypes.TimestampProto(m.Time) if err != nil { return nil, errToRPCError(err) } resp.Result = append(resp.Result, &row) } return &resp, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "GetGatewayStats", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "GetGatewayStatsRequest", ")", "(", "*", "ns", ".", "GetGatewayStatsResponse", ",", "error", ")", "{", "gatewayID", ":=", "helpers", ".", "GetGatewayID", "(", "req", ")", "\n\n", "start", ",", "err", ":=", "ptypes", ".", "Timestamp", "(", "req", ".", "StartTimestamp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "end", ",", "err", ":=", "ptypes", ".", "Timestamp", "(", "req", ".", "EndTimestamp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "metrics", ",", "err", ":=", "storage", ".", "GetMetrics", "(", "storage", ".", "RedisPool", "(", ")", ",", "storage", ".", "AggregationInterval", "(", "req", ".", "Interval", ".", "String", "(", ")", ")", ",", "\"", "\"", "+", "gatewayID", ".", "String", "(", ")", ",", "start", ",", "end", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "var", "resp", "ns", ".", "GetGatewayStatsResponse", "\n\n", "for", "_", ",", "m", ":=", "range", "metrics", "{", "row", ":=", "ns", ".", "GatewayStats", "{", "RxPacketsReceived", ":", "int32", "(", "m", ".", "Metrics", "[", "\"", "\"", "]", ")", ",", "RxPacketsReceivedOk", ":", "int32", "(", "m", ".", "Metrics", "[", "\"", "\"", "]", ")", ",", "TxPacketsReceived", ":", "int32", "(", "m", ".", "Metrics", "[", "\"", "\"", "]", ")", ",", "TxPacketsEmitted", ":", "int32", "(", "m", ".", "Metrics", "[", "\"", "\"", "]", ")", ",", "}", "\n\n", "row", ".", "Timestamp", ",", "err", "=", "ptypes", ".", "TimestampProto", "(", "m", ".", "Time", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "resp", ".", "Result", "=", "append", "(", "resp", ".", "Result", ",", "&", "row", ")", "\n", "}", "\n\n", "return", "&", "resp", ",", "nil", "\n", "}" ]
// GetGatewayStats returns stats of an existing gateway.
[ "GetGatewayStats", "returns", "stats", "of", "an", "existing", "gateway", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1000-L1037
train
brocaar/loraserver
internal/api/network_server.go
StreamFrameLogsForGateway
func (n *NetworkServerAPI) StreamFrameLogsForGateway(req *ns.StreamFrameLogsForGatewayRequest, srv ns.NetworkServerService_StreamFrameLogsForGatewayServer) error { frameLogChan := make(chan framelog.FrameLog) var id lorawan.EUI64 copy(id[:], req.GatewayId) go func() { err := framelog.GetFrameLogForGateway(srv.Context(), storage.RedisPool(), id, frameLogChan) if err != nil { log.WithError(err).Error("get frame-log for gateway error") } close(frameLogChan) }() for fl := range frameLogChan { resp := ns.StreamFrameLogsForGatewayResponse{} if fl.UplinkFrame != nil { resp.Frame = &ns.StreamFrameLogsForGatewayResponse_UplinkFrameSet{ UplinkFrameSet: fl.UplinkFrame, } } if fl.DownlinkFrame != nil { resp.Frame = &ns.StreamFrameLogsForGatewayResponse_DownlinkFrame{ DownlinkFrame: fl.DownlinkFrame, } } if err := srv.Send(&resp); err != nil { log.WithError(err).Error("error sending frame-log response") } } return nil }
go
func (n *NetworkServerAPI) StreamFrameLogsForGateway(req *ns.StreamFrameLogsForGatewayRequest, srv ns.NetworkServerService_StreamFrameLogsForGatewayServer) error { frameLogChan := make(chan framelog.FrameLog) var id lorawan.EUI64 copy(id[:], req.GatewayId) go func() { err := framelog.GetFrameLogForGateway(srv.Context(), storage.RedisPool(), id, frameLogChan) if err != nil { log.WithError(err).Error("get frame-log for gateway error") } close(frameLogChan) }() for fl := range frameLogChan { resp := ns.StreamFrameLogsForGatewayResponse{} if fl.UplinkFrame != nil { resp.Frame = &ns.StreamFrameLogsForGatewayResponse_UplinkFrameSet{ UplinkFrameSet: fl.UplinkFrame, } } if fl.DownlinkFrame != nil { resp.Frame = &ns.StreamFrameLogsForGatewayResponse_DownlinkFrame{ DownlinkFrame: fl.DownlinkFrame, } } if err := srv.Send(&resp); err != nil { log.WithError(err).Error("error sending frame-log response") } } return nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "StreamFrameLogsForGateway", "(", "req", "*", "ns", ".", "StreamFrameLogsForGatewayRequest", ",", "srv", "ns", ".", "NetworkServerService_StreamFrameLogsForGatewayServer", ")", "error", "{", "frameLogChan", ":=", "make", "(", "chan", "framelog", ".", "FrameLog", ")", "\n", "var", "id", "lorawan", ".", "EUI64", "\n", "copy", "(", "id", "[", ":", "]", ",", "req", ".", "GatewayId", ")", "\n\n", "go", "func", "(", ")", "{", "err", ":=", "framelog", ".", "GetFrameLogForGateway", "(", "srv", ".", "Context", "(", ")", ",", "storage", ".", "RedisPool", "(", ")", ",", "id", ",", "frameLogChan", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "close", "(", "frameLogChan", ")", "\n", "}", "(", ")", "\n\n", "for", "fl", ":=", "range", "frameLogChan", "{", "resp", ":=", "ns", ".", "StreamFrameLogsForGatewayResponse", "{", "}", "\n\n", "if", "fl", ".", "UplinkFrame", "!=", "nil", "{", "resp", ".", "Frame", "=", "&", "ns", ".", "StreamFrameLogsForGatewayResponse_UplinkFrameSet", "{", "UplinkFrameSet", ":", "fl", ".", "UplinkFrame", ",", "}", "\n", "}", "\n\n", "if", "fl", ".", "DownlinkFrame", "!=", "nil", "{", "resp", ".", "Frame", "=", "&", "ns", ".", "StreamFrameLogsForGatewayResponse_DownlinkFrame", "{", "DownlinkFrame", ":", "fl", ".", "DownlinkFrame", ",", "}", "\n", "}", "\n\n", "if", "err", ":=", "srv", ".", "Send", "(", "&", "resp", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// StreamFrameLogsForGateway returns a stream of frames seen by the given gateway.
[ "StreamFrameLogsForGateway", "returns", "a", "stream", "of", "frames", "seen", "by", "the", "given", "gateway", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1040-L1074
train
brocaar/loraserver
internal/api/network_server.go
StreamFrameLogsForDevice
func (n *NetworkServerAPI) StreamFrameLogsForDevice(req *ns.StreamFrameLogsForDeviceRequest, srv ns.NetworkServerService_StreamFrameLogsForDeviceServer) error { frameLogChan := make(chan framelog.FrameLog) var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) go func() { err := framelog.GetFrameLogForDevice(srv.Context(), storage.RedisPool(), devEUI, frameLogChan) if err != nil { log.WithError(err).Error("get frame-log for device error") } close(frameLogChan) }() for fl := range frameLogChan { resp := ns.StreamFrameLogsForDeviceResponse{} if fl.UplinkFrame != nil { resp.Frame = &ns.StreamFrameLogsForDeviceResponse_UplinkFrameSet{ UplinkFrameSet: fl.UplinkFrame, } } if fl.DownlinkFrame != nil { resp.Frame = &ns.StreamFrameLogsForDeviceResponse_DownlinkFrame{ DownlinkFrame: fl.DownlinkFrame, } } if err := srv.Send(&resp); err != nil { log.WithError(err).Error("error sending frame-log response") } } return nil }
go
func (n *NetworkServerAPI) StreamFrameLogsForDevice(req *ns.StreamFrameLogsForDeviceRequest, srv ns.NetworkServerService_StreamFrameLogsForDeviceServer) error { frameLogChan := make(chan framelog.FrameLog) var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) go func() { err := framelog.GetFrameLogForDevice(srv.Context(), storage.RedisPool(), devEUI, frameLogChan) if err != nil { log.WithError(err).Error("get frame-log for device error") } close(frameLogChan) }() for fl := range frameLogChan { resp := ns.StreamFrameLogsForDeviceResponse{} if fl.UplinkFrame != nil { resp.Frame = &ns.StreamFrameLogsForDeviceResponse_UplinkFrameSet{ UplinkFrameSet: fl.UplinkFrame, } } if fl.DownlinkFrame != nil { resp.Frame = &ns.StreamFrameLogsForDeviceResponse_DownlinkFrame{ DownlinkFrame: fl.DownlinkFrame, } } if err := srv.Send(&resp); err != nil { log.WithError(err).Error("error sending frame-log response") } } return nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "StreamFrameLogsForDevice", "(", "req", "*", "ns", ".", "StreamFrameLogsForDeviceRequest", ",", "srv", "ns", ".", "NetworkServerService_StreamFrameLogsForDeviceServer", ")", "error", "{", "frameLogChan", ":=", "make", "(", "chan", "framelog", ".", "FrameLog", ")", "\n", "var", "devEUI", "lorawan", ".", "EUI64", "\n", "copy", "(", "devEUI", "[", ":", "]", ",", "req", ".", "DevEui", ")", "\n\n", "go", "func", "(", ")", "{", "err", ":=", "framelog", ".", "GetFrameLogForDevice", "(", "srv", ".", "Context", "(", ")", ",", "storage", ".", "RedisPool", "(", ")", ",", "devEUI", ",", "frameLogChan", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "close", "(", "frameLogChan", ")", "\n", "}", "(", ")", "\n\n", "for", "fl", ":=", "range", "frameLogChan", "{", "resp", ":=", "ns", ".", "StreamFrameLogsForDeviceResponse", "{", "}", "\n\n", "if", "fl", ".", "UplinkFrame", "!=", "nil", "{", "resp", ".", "Frame", "=", "&", "ns", ".", "StreamFrameLogsForDeviceResponse_UplinkFrameSet", "{", "UplinkFrameSet", ":", "fl", ".", "UplinkFrame", ",", "}", "\n", "}", "\n\n", "if", "fl", ".", "DownlinkFrame", "!=", "nil", "{", "resp", ".", "Frame", "=", "&", "ns", ".", "StreamFrameLogsForDeviceResponse_DownlinkFrame", "{", "DownlinkFrame", ":", "fl", ".", "DownlinkFrame", ",", "}", "\n", "}", "\n\n", "if", "err", ":=", "srv", ".", "Send", "(", "&", "resp", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// StreamFrameLogsForDevice returns a stream of frames seen by the given device.
[ "StreamFrameLogsForDevice", "returns", "a", "stream", "of", "frames", "seen", "by", "the", "given", "device", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1077-L1111
train
brocaar/loraserver
internal/api/network_server.go
GetGatewayProfile
func (n *NetworkServerAPI) GetGatewayProfile(ctx context.Context, req *ns.GetGatewayProfileRequest) (*ns.GetGatewayProfileResponse, error) { var gpID uuid.UUID copy(gpID[:], req.Id) gc, err := storage.GetGatewayProfile(storage.DB(), gpID) if err != nil { return nil, errToRPCError(err) } out := ns.GetGatewayProfileResponse{ GatewayProfile: &ns.GatewayProfile{ Id: gc.ID.Bytes(), }, } out.CreatedAt, err = ptypes.TimestampProto(gc.CreatedAt) if err != nil { return nil, errToRPCError(err) } out.UpdatedAt, err = ptypes.TimestampProto(gc.UpdatedAt) if err != nil { return nil, errToRPCError(err) } for _, c := range gc.Channels { out.GatewayProfile.Channels = append(out.GatewayProfile.Channels, uint32(c)) } for _, ec := range gc.ExtraChannels { c := ns.GatewayProfileExtraChannel{ Frequency: uint32(ec.Frequency), Bandwidth: uint32(ec.Bandwidth), Bitrate: uint32(ec.Bitrate), } switch ec.Modulation { case storage.ModulationFSK: c.Modulation = common.Modulation_FSK default: c.Modulation = common.Modulation_LORA } for _, sf := range ec.SpreadingFactors { c.SpreadingFactors = append(c.SpreadingFactors, uint32(sf)) } out.GatewayProfile.ExtraChannels = append(out.GatewayProfile.ExtraChannels, &c) } return &out, nil }
go
func (n *NetworkServerAPI) GetGatewayProfile(ctx context.Context, req *ns.GetGatewayProfileRequest) (*ns.GetGatewayProfileResponse, error) { var gpID uuid.UUID copy(gpID[:], req.Id) gc, err := storage.GetGatewayProfile(storage.DB(), gpID) if err != nil { return nil, errToRPCError(err) } out := ns.GetGatewayProfileResponse{ GatewayProfile: &ns.GatewayProfile{ Id: gc.ID.Bytes(), }, } out.CreatedAt, err = ptypes.TimestampProto(gc.CreatedAt) if err != nil { return nil, errToRPCError(err) } out.UpdatedAt, err = ptypes.TimestampProto(gc.UpdatedAt) if err != nil { return nil, errToRPCError(err) } for _, c := range gc.Channels { out.GatewayProfile.Channels = append(out.GatewayProfile.Channels, uint32(c)) } for _, ec := range gc.ExtraChannels { c := ns.GatewayProfileExtraChannel{ Frequency: uint32(ec.Frequency), Bandwidth: uint32(ec.Bandwidth), Bitrate: uint32(ec.Bitrate), } switch ec.Modulation { case storage.ModulationFSK: c.Modulation = common.Modulation_FSK default: c.Modulation = common.Modulation_LORA } for _, sf := range ec.SpreadingFactors { c.SpreadingFactors = append(c.SpreadingFactors, uint32(sf)) } out.GatewayProfile.ExtraChannels = append(out.GatewayProfile.ExtraChannels, &c) } return &out, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "GetGatewayProfile", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "GetGatewayProfileRequest", ")", "(", "*", "ns", ".", "GetGatewayProfileResponse", ",", "error", ")", "{", "var", "gpID", "uuid", ".", "UUID", "\n", "copy", "(", "gpID", "[", ":", "]", ",", "req", ".", "Id", ")", "\n\n", "gc", ",", "err", ":=", "storage", ".", "GetGatewayProfile", "(", "storage", ".", "DB", "(", ")", ",", "gpID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "out", ":=", "ns", ".", "GetGatewayProfileResponse", "{", "GatewayProfile", ":", "&", "ns", ".", "GatewayProfile", "{", "Id", ":", "gc", ".", "ID", ".", "Bytes", "(", ")", ",", "}", ",", "}", "\n\n", "out", ".", "CreatedAt", ",", "err", "=", "ptypes", ".", "TimestampProto", "(", "gc", ".", "CreatedAt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "out", ".", "UpdatedAt", ",", "err", "=", "ptypes", ".", "TimestampProto", "(", "gc", ".", "UpdatedAt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "c", ":=", "range", "gc", ".", "Channels", "{", "out", ".", "GatewayProfile", ".", "Channels", "=", "append", "(", "out", ".", "GatewayProfile", ".", "Channels", ",", "uint32", "(", "c", ")", ")", "\n", "}", "\n\n", "for", "_", ",", "ec", ":=", "range", "gc", ".", "ExtraChannels", "{", "c", ":=", "ns", ".", "GatewayProfileExtraChannel", "{", "Frequency", ":", "uint32", "(", "ec", ".", "Frequency", ")", ",", "Bandwidth", ":", "uint32", "(", "ec", ".", "Bandwidth", ")", ",", "Bitrate", ":", "uint32", "(", "ec", ".", "Bitrate", ")", ",", "}", "\n\n", "switch", "ec", ".", "Modulation", "{", "case", "storage", ".", "ModulationFSK", ":", "c", ".", "Modulation", "=", "common", ".", "Modulation_FSK", "\n", "default", ":", "c", ".", "Modulation", "=", "common", ".", "Modulation_LORA", "\n", "}", "\n\n", "for", "_", ",", "sf", ":=", "range", "ec", ".", "SpreadingFactors", "{", "c", ".", "SpreadingFactors", "=", "append", "(", "c", ".", "SpreadingFactors", ",", "uint32", "(", "sf", ")", ")", "\n", "}", "\n\n", "out", ".", "GatewayProfile", ".", "ExtraChannels", "=", "append", "(", "out", ".", "GatewayProfile", ".", "ExtraChannels", ",", "&", "c", ")", "\n", "}", "\n\n", "return", "&", "out", ",", "nil", "\n", "}" ]
// GetGatewayProfile returns the gateway-profile given an id.
[ "GetGatewayProfile", "returns", "the", "gateway", "-", "profile", "given", "an", "id", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1162-L1213
train
brocaar/loraserver
internal/api/network_server.go
UpdateGatewayProfile
func (n *NetworkServerAPI) UpdateGatewayProfile(ctx context.Context, req *ns.UpdateGatewayProfileRequest) (*empty.Empty, error) { if req.GatewayProfile == nil { return nil, grpc.Errorf(codes.InvalidArgument, "gateway_profile must not be nil") } var gpID uuid.UUID copy(gpID[:], req.GatewayProfile.Id) gc, err := storage.GetGatewayProfile(storage.DB(), gpID) if err != nil { return nil, errToRPCError(err) } gc.Channels = []int64{} for _, c := range req.GatewayProfile.Channels { gc.Channels = append(gc.Channels, int64(c)) } gc.ExtraChannels = []storage.ExtraChannel{} for _, ec := range req.GatewayProfile.ExtraChannels { c := storage.ExtraChannel{ Frequency: int(ec.Frequency), Bandwidth: int(ec.Bandwidth), Bitrate: int(ec.Bitrate), } switch ec.Modulation { case common.Modulation_FSK: c.Modulation = storage.ModulationFSK default: c.Modulation = storage.ModulationLoRa } for _, sf := range ec.SpreadingFactors { c.SpreadingFactors = append(c.SpreadingFactors, int64(sf)) } gc.ExtraChannels = append(gc.ExtraChannels, c) } err = storage.Transaction(func(tx sqlx.Ext) error { return storage.UpdateGatewayProfile(tx, &gc) }) if err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) UpdateGatewayProfile(ctx context.Context, req *ns.UpdateGatewayProfileRequest) (*empty.Empty, error) { if req.GatewayProfile == nil { return nil, grpc.Errorf(codes.InvalidArgument, "gateway_profile must not be nil") } var gpID uuid.UUID copy(gpID[:], req.GatewayProfile.Id) gc, err := storage.GetGatewayProfile(storage.DB(), gpID) if err != nil { return nil, errToRPCError(err) } gc.Channels = []int64{} for _, c := range req.GatewayProfile.Channels { gc.Channels = append(gc.Channels, int64(c)) } gc.ExtraChannels = []storage.ExtraChannel{} for _, ec := range req.GatewayProfile.ExtraChannels { c := storage.ExtraChannel{ Frequency: int(ec.Frequency), Bandwidth: int(ec.Bandwidth), Bitrate: int(ec.Bitrate), } switch ec.Modulation { case common.Modulation_FSK: c.Modulation = storage.ModulationFSK default: c.Modulation = storage.ModulationLoRa } for _, sf := range ec.SpreadingFactors { c.SpreadingFactors = append(c.SpreadingFactors, int64(sf)) } gc.ExtraChannels = append(gc.ExtraChannels, c) } err = storage.Transaction(func(tx sqlx.Ext) error { return storage.UpdateGatewayProfile(tx, &gc) }) if err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "UpdateGatewayProfile", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "UpdateGatewayProfileRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "if", "req", ".", "GatewayProfile", "==", "nil", "{", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "gpID", "uuid", ".", "UUID", "\n", "copy", "(", "gpID", "[", ":", "]", ",", "req", ".", "GatewayProfile", ".", "Id", ")", "\n\n", "gc", ",", "err", ":=", "storage", ".", "GetGatewayProfile", "(", "storage", ".", "DB", "(", ")", ",", "gpID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "gc", ".", "Channels", "=", "[", "]", "int64", "{", "}", "\n", "for", "_", ",", "c", ":=", "range", "req", ".", "GatewayProfile", ".", "Channels", "{", "gc", ".", "Channels", "=", "append", "(", "gc", ".", "Channels", ",", "int64", "(", "c", ")", ")", "\n", "}", "\n\n", "gc", ".", "ExtraChannels", "=", "[", "]", "storage", ".", "ExtraChannel", "{", "}", "\n", "for", "_", ",", "ec", ":=", "range", "req", ".", "GatewayProfile", ".", "ExtraChannels", "{", "c", ":=", "storage", ".", "ExtraChannel", "{", "Frequency", ":", "int", "(", "ec", ".", "Frequency", ")", ",", "Bandwidth", ":", "int", "(", "ec", ".", "Bandwidth", ")", ",", "Bitrate", ":", "int", "(", "ec", ".", "Bitrate", ")", ",", "}", "\n\n", "switch", "ec", ".", "Modulation", "{", "case", "common", ".", "Modulation_FSK", ":", "c", ".", "Modulation", "=", "storage", ".", "ModulationFSK", "\n", "default", ":", "c", ".", "Modulation", "=", "storage", ".", "ModulationLoRa", "\n", "}", "\n\n", "for", "_", ",", "sf", ":=", "range", "ec", ".", "SpreadingFactors", "{", "c", ".", "SpreadingFactors", "=", "append", "(", "c", ".", "SpreadingFactors", ",", "int64", "(", "sf", ")", ")", "\n", "}", "\n\n", "gc", ".", "ExtraChannels", "=", "append", "(", "gc", ".", "ExtraChannels", ",", "c", ")", "\n", "}", "\n\n", "err", "=", "storage", ".", "Transaction", "(", "func", "(", "tx", "sqlx", ".", "Ext", ")", "error", "{", "return", "storage", ".", "UpdateGatewayProfile", "(", "tx", ",", "&", "gc", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// UpdateGatewayProfile updates the given gateway-profile.
[ "UpdateGatewayProfile", "updates", "the", "given", "gateway", "-", "profile", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1216-L1264
train
brocaar/loraserver
internal/api/network_server.go
DeleteGatewayProfile
func (n *NetworkServerAPI) DeleteGatewayProfile(ctx context.Context, req *ns.DeleteGatewayProfileRequest) (*empty.Empty, error) { var gpID uuid.UUID copy(gpID[:], req.Id) if err := storage.DeleteGatewayProfile(storage.DB(), gpID); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) DeleteGatewayProfile(ctx context.Context, req *ns.DeleteGatewayProfileRequest) (*empty.Empty, error) { var gpID uuid.UUID copy(gpID[:], req.Id) if err := storage.DeleteGatewayProfile(storage.DB(), gpID); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "DeleteGatewayProfile", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "DeleteGatewayProfileRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "var", "gpID", "uuid", ".", "UUID", "\n", "copy", "(", "gpID", "[", ":", "]", ",", "req", ".", "Id", ")", "\n\n", "if", "err", ":=", "storage", ".", "DeleteGatewayProfile", "(", "storage", ".", "DB", "(", ")", ",", "gpID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// DeleteGatewayProfile deletes the gateway-profile matching a given id.
[ "DeleteGatewayProfile", "deletes", "the", "gateway", "-", "profile", "matching", "a", "given", "id", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1267-L1276
train
brocaar/loraserver
internal/api/network_server.go
FlushDeviceQueueForDevEUI
func (n *NetworkServerAPI) FlushDeviceQueueForDevEUI(ctx context.Context, req *ns.FlushDeviceQueueForDevEUIRequest) (*empty.Empty, error) { var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) err := storage.FlushDeviceQueueForDevEUI(storage.DB(), devEUI) if err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) FlushDeviceQueueForDevEUI(ctx context.Context, req *ns.FlushDeviceQueueForDevEUIRequest) (*empty.Empty, error) { var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) err := storage.FlushDeviceQueueForDevEUI(storage.DB(), devEUI) if err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "FlushDeviceQueueForDevEUI", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "FlushDeviceQueueForDevEUIRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "var", "devEUI", "lorawan", ".", "EUI64", "\n", "copy", "(", "devEUI", "[", ":", "]", ",", "req", ".", "DevEui", ")", "\n\n", "err", ":=", "storage", ".", "FlushDeviceQueueForDevEUI", "(", "storage", ".", "DB", "(", ")", ",", "devEUI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// FlushDeviceQueueForDevEUI flushes the device-queue for the given DevEUI.
[ "FlushDeviceQueueForDevEUI", "flushes", "the", "device", "-", "queue", "for", "the", "given", "DevEUI", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1360-L1370
train
brocaar/loraserver
internal/api/network_server.go
GetDeviceQueueItemsForDevEUI
func (n *NetworkServerAPI) GetDeviceQueueItemsForDevEUI(ctx context.Context, req *ns.GetDeviceQueueItemsForDevEUIRequest) (*ns.GetDeviceQueueItemsForDevEUIResponse, error) { var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) items, err := storage.GetDeviceQueueItemsForDevEUI(storage.DB(), devEUI) if err != nil { return nil, errToRPCError(err) } var out ns.GetDeviceQueueItemsForDevEUIResponse for i := range items { qi := ns.DeviceQueueItem{ DevAddr: items[i].DevAddr[:], DevEui: items[i].DevEUI[:], FrmPayload: items[i].FRMPayload, FCnt: items[i].FCnt, FPort: uint32(items[i].FPort), Confirmed: items[i].Confirmed, } out.Items = append(out.Items, &qi) } return &out, nil }
go
func (n *NetworkServerAPI) GetDeviceQueueItemsForDevEUI(ctx context.Context, req *ns.GetDeviceQueueItemsForDevEUIRequest) (*ns.GetDeviceQueueItemsForDevEUIResponse, error) { var devEUI lorawan.EUI64 copy(devEUI[:], req.DevEui) items, err := storage.GetDeviceQueueItemsForDevEUI(storage.DB(), devEUI) if err != nil { return nil, errToRPCError(err) } var out ns.GetDeviceQueueItemsForDevEUIResponse for i := range items { qi := ns.DeviceQueueItem{ DevAddr: items[i].DevAddr[:], DevEui: items[i].DevEUI[:], FrmPayload: items[i].FRMPayload, FCnt: items[i].FCnt, FPort: uint32(items[i].FPort), Confirmed: items[i].Confirmed, } out.Items = append(out.Items, &qi) } return &out, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "GetDeviceQueueItemsForDevEUI", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "GetDeviceQueueItemsForDevEUIRequest", ")", "(", "*", "ns", ".", "GetDeviceQueueItemsForDevEUIResponse", ",", "error", ")", "{", "var", "devEUI", "lorawan", ".", "EUI64", "\n", "copy", "(", "devEUI", "[", ":", "]", ",", "req", ".", "DevEui", ")", "\n\n", "items", ",", "err", ":=", "storage", ".", "GetDeviceQueueItemsForDevEUI", "(", "storage", ".", "DB", "(", ")", ",", "devEUI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "var", "out", "ns", ".", "GetDeviceQueueItemsForDevEUIResponse", "\n", "for", "i", ":=", "range", "items", "{", "qi", ":=", "ns", ".", "DeviceQueueItem", "{", "DevAddr", ":", "items", "[", "i", "]", ".", "DevAddr", "[", ":", "]", ",", "DevEui", ":", "items", "[", "i", "]", ".", "DevEUI", "[", ":", "]", ",", "FrmPayload", ":", "items", "[", "i", "]", ".", "FRMPayload", ",", "FCnt", ":", "items", "[", "i", "]", ".", "FCnt", ",", "FPort", ":", "uint32", "(", "items", "[", "i", "]", ".", "FPort", ")", ",", "Confirmed", ":", "items", "[", "i", "]", ".", "Confirmed", ",", "}", "\n\n", "out", ".", "Items", "=", "append", "(", "out", ".", "Items", ",", "&", "qi", ")", "\n", "}", "\n\n", "return", "&", "out", ",", "nil", "\n", "}" ]
// GetDeviceQueueItemsForDevEUI returns all device-queue items for the given DevEUI.
[ "GetDeviceQueueItemsForDevEUI", "returns", "all", "device", "-", "queue", "items", "for", "the", "given", "DevEUI", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1373-L1397
train
brocaar/loraserver
internal/api/network_server.go
GetNextDownlinkFCntForDevEUI
func (n *NetworkServerAPI) GetNextDownlinkFCntForDevEUI(ctx context.Context, req *ns.GetNextDownlinkFCntForDevEUIRequest) (*ns.GetNextDownlinkFCntForDevEUIResponse, error) { var devEUI lorawan.EUI64 var resp ns.GetNextDownlinkFCntForDevEUIResponse copy(devEUI[:], req.DevEui) ds, err := storage.GetDeviceSession(storage.RedisPool(), devEUI) if err != nil { return nil, errToRPCError(err) } if ds.GetMACVersion() == lorawan.LoRaWAN1_0 { resp.FCnt = ds.NFCntDown } else { resp.FCnt = ds.AFCntDown } items, err := storage.GetDeviceQueueItemsForDevEUI(storage.DB(), devEUI) if err != nil { return nil, errToRPCError(err) } if count := len(items); count != 0 { resp.FCnt = items[count-1].FCnt + 1 // we want the next usable frame-counter } return &resp, nil }
go
func (n *NetworkServerAPI) GetNextDownlinkFCntForDevEUI(ctx context.Context, req *ns.GetNextDownlinkFCntForDevEUIRequest) (*ns.GetNextDownlinkFCntForDevEUIResponse, error) { var devEUI lorawan.EUI64 var resp ns.GetNextDownlinkFCntForDevEUIResponse copy(devEUI[:], req.DevEui) ds, err := storage.GetDeviceSession(storage.RedisPool(), devEUI) if err != nil { return nil, errToRPCError(err) } if ds.GetMACVersion() == lorawan.LoRaWAN1_0 { resp.FCnt = ds.NFCntDown } else { resp.FCnt = ds.AFCntDown } items, err := storage.GetDeviceQueueItemsForDevEUI(storage.DB(), devEUI) if err != nil { return nil, errToRPCError(err) } if count := len(items); count != 0 { resp.FCnt = items[count-1].FCnt + 1 // we want the next usable frame-counter } return &resp, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "GetNextDownlinkFCntForDevEUI", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "GetNextDownlinkFCntForDevEUIRequest", ")", "(", "*", "ns", ".", "GetNextDownlinkFCntForDevEUIResponse", ",", "error", ")", "{", "var", "devEUI", "lorawan", ".", "EUI64", "\n", "var", "resp", "ns", ".", "GetNextDownlinkFCntForDevEUIResponse", "\n\n", "copy", "(", "devEUI", "[", ":", "]", ",", "req", ".", "DevEui", ")", "\n\n", "ds", ",", "err", ":=", "storage", ".", "GetDeviceSession", "(", "storage", ".", "RedisPool", "(", ")", ",", "devEUI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "if", "ds", ".", "GetMACVersion", "(", ")", "==", "lorawan", ".", "LoRaWAN1_0", "{", "resp", ".", "FCnt", "=", "ds", ".", "NFCntDown", "\n", "}", "else", "{", "resp", ".", "FCnt", "=", "ds", ".", "AFCntDown", "\n", "}", "\n\n", "items", ",", "err", ":=", "storage", ".", "GetDeviceQueueItemsForDevEUI", "(", "storage", ".", "DB", "(", ")", ",", "devEUI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n", "if", "count", ":=", "len", "(", "items", ")", ";", "count", "!=", "0", "{", "resp", ".", "FCnt", "=", "items", "[", "count", "-", "1", "]", ".", "FCnt", "+", "1", "// we want the next usable frame-counter", "\n", "}", "\n\n", "return", "&", "resp", ",", "nil", "\n", "}" ]
// GetNextDownlinkFCntForDevEUI returns the next FCnt that must be used. // This also takes device-queue items for the given DevEUI into consideration. // In case the device is not activated, this will return an error as no // device-session exists.
[ "GetNextDownlinkFCntForDevEUI", "returns", "the", "next", "FCnt", "that", "must", "be", "used", ".", "This", "also", "takes", "device", "-", "queue", "items", "for", "the", "given", "DevEUI", "into", "consideration", ".", "In", "case", "the", "device", "is", "not", "activated", "this", "will", "return", "an", "error", "as", "no", "device", "-", "session", "exists", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1403-L1429
train
brocaar/loraserver
internal/api/network_server.go
CreateMulticastGroup
func (n *NetworkServerAPI) CreateMulticastGroup(ctx context.Context, req *ns.CreateMulticastGroupRequest) (*ns.CreateMulticastGroupResponse, error) { if req.MulticastGroup == nil { return nil, grpc.Errorf(codes.InvalidArgument, "multicast_group must not be nil") } mg := storage.MulticastGroup{ FCnt: req.MulticastGroup.FCnt, DR: int(req.MulticastGroup.Dr), Frequency: int(req.MulticastGroup.Frequency), PingSlotPeriod: int(req.MulticastGroup.PingSlotPeriod), } switch req.MulticastGroup.GroupType { case ns.MulticastGroupType_CLASS_B: mg.GroupType = storage.MulticastGroupB case ns.MulticastGroupType_CLASS_C: mg.GroupType = storage.MulticastGroupC default: return nil, grpc.Errorf(codes.InvalidArgument, "invalid group_type") } copy(mg.ID[:], req.MulticastGroup.Id) copy(mg.MCAddr[:], req.MulticastGroup.McAddr) copy(mg.MCNwkSKey[:], req.MulticastGroup.McNwkSKey) copy(mg.ServiceProfileID[:], req.MulticastGroup.ServiceProfileId) copy(mg.RoutingProfileID[:], req.MulticastGroup.RoutingProfileId) if err := storage.CreateMulticastGroup(storage.DB(), &mg); err != nil { return nil, errToRPCError(err) } return &ns.CreateMulticastGroupResponse{ Id: mg.ID.Bytes(), }, nil }
go
func (n *NetworkServerAPI) CreateMulticastGroup(ctx context.Context, req *ns.CreateMulticastGroupRequest) (*ns.CreateMulticastGroupResponse, error) { if req.MulticastGroup == nil { return nil, grpc.Errorf(codes.InvalidArgument, "multicast_group must not be nil") } mg := storage.MulticastGroup{ FCnt: req.MulticastGroup.FCnt, DR: int(req.MulticastGroup.Dr), Frequency: int(req.MulticastGroup.Frequency), PingSlotPeriod: int(req.MulticastGroup.PingSlotPeriod), } switch req.MulticastGroup.GroupType { case ns.MulticastGroupType_CLASS_B: mg.GroupType = storage.MulticastGroupB case ns.MulticastGroupType_CLASS_C: mg.GroupType = storage.MulticastGroupC default: return nil, grpc.Errorf(codes.InvalidArgument, "invalid group_type") } copy(mg.ID[:], req.MulticastGroup.Id) copy(mg.MCAddr[:], req.MulticastGroup.McAddr) copy(mg.MCNwkSKey[:], req.MulticastGroup.McNwkSKey) copy(mg.ServiceProfileID[:], req.MulticastGroup.ServiceProfileId) copy(mg.RoutingProfileID[:], req.MulticastGroup.RoutingProfileId) if err := storage.CreateMulticastGroup(storage.DB(), &mg); err != nil { return nil, errToRPCError(err) } return &ns.CreateMulticastGroupResponse{ Id: mg.ID.Bytes(), }, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "CreateMulticastGroup", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "CreateMulticastGroupRequest", ")", "(", "*", "ns", ".", "CreateMulticastGroupResponse", ",", "error", ")", "{", "if", "req", ".", "MulticastGroup", "==", "nil", "{", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "mg", ":=", "storage", ".", "MulticastGroup", "{", "FCnt", ":", "req", ".", "MulticastGroup", ".", "FCnt", ",", "DR", ":", "int", "(", "req", ".", "MulticastGroup", ".", "Dr", ")", ",", "Frequency", ":", "int", "(", "req", ".", "MulticastGroup", ".", "Frequency", ")", ",", "PingSlotPeriod", ":", "int", "(", "req", ".", "MulticastGroup", ".", "PingSlotPeriod", ")", ",", "}", "\n\n", "switch", "req", ".", "MulticastGroup", ".", "GroupType", "{", "case", "ns", ".", "MulticastGroupType_CLASS_B", ":", "mg", ".", "GroupType", "=", "storage", ".", "MulticastGroupB", "\n", "case", "ns", ".", "MulticastGroupType_CLASS_C", ":", "mg", ".", "GroupType", "=", "storage", ".", "MulticastGroupC", "\n", "default", ":", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "copy", "(", "mg", ".", "ID", "[", ":", "]", ",", "req", ".", "MulticastGroup", ".", "Id", ")", "\n", "copy", "(", "mg", ".", "MCAddr", "[", ":", "]", ",", "req", ".", "MulticastGroup", ".", "McAddr", ")", "\n", "copy", "(", "mg", ".", "MCNwkSKey", "[", ":", "]", ",", "req", ".", "MulticastGroup", ".", "McNwkSKey", ")", "\n", "copy", "(", "mg", ".", "ServiceProfileID", "[", ":", "]", ",", "req", ".", "MulticastGroup", ".", "ServiceProfileId", ")", "\n", "copy", "(", "mg", ".", "RoutingProfileID", "[", ":", "]", ",", "req", ".", "MulticastGroup", ".", "RoutingProfileId", ")", "\n\n", "if", "err", ":=", "storage", ".", "CreateMulticastGroup", "(", "storage", ".", "DB", "(", ")", ",", "&", "mg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "ns", ".", "CreateMulticastGroupResponse", "{", "Id", ":", "mg", ".", "ID", ".", "Bytes", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// CreateMulticastGroup creates the given multicast-group.
[ "CreateMulticastGroup", "creates", "the", "given", "multicast", "-", "group", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1432-L1466
train
brocaar/loraserver
internal/api/network_server.go
GetMulticastGroup
func (n *NetworkServerAPI) GetMulticastGroup(ctx context.Context, req *ns.GetMulticastGroupRequest) (*ns.GetMulticastGroupResponse, error) { var mgID uuid.UUID copy(mgID[:], req.Id) mg, err := storage.GetMulticastGroup(storage.DB(), mgID, false) if err != nil { return nil, errToRPCError(err) } resp := ns.GetMulticastGroupResponse{ MulticastGroup: &ns.MulticastGroup{ Id: mg.ID.Bytes(), McAddr: mg.MCAddr[:], McNwkSKey: mg.MCNwkSKey[:], FCnt: mg.FCnt, Dr: uint32(mg.DR), Frequency: uint32(mg.Frequency), PingSlotPeriod: uint32(mg.PingSlotPeriod), ServiceProfileId: mg.ServiceProfileID.Bytes(), RoutingProfileId: mg.RoutingProfileID.Bytes(), }, } switch mg.GroupType { case storage.MulticastGroupB: resp.MulticastGroup.GroupType = ns.MulticastGroupType_CLASS_B case storage.MulticastGroupC: resp.MulticastGroup.GroupType = ns.MulticastGroupType_CLASS_C default: return nil, grpc.Errorf(codes.Internal, "invalid group-type: %s", mg.GroupType) } resp.CreatedAt, err = ptypes.TimestampProto(mg.CreatedAt) if err != nil { return nil, errToRPCError(err) } resp.UpdatedAt, err = ptypes.TimestampProto(mg.UpdatedAt) if err != nil { return nil, errToRPCError(err) } return &resp, nil }
go
func (n *NetworkServerAPI) GetMulticastGroup(ctx context.Context, req *ns.GetMulticastGroupRequest) (*ns.GetMulticastGroupResponse, error) { var mgID uuid.UUID copy(mgID[:], req.Id) mg, err := storage.GetMulticastGroup(storage.DB(), mgID, false) if err != nil { return nil, errToRPCError(err) } resp := ns.GetMulticastGroupResponse{ MulticastGroup: &ns.MulticastGroup{ Id: mg.ID.Bytes(), McAddr: mg.MCAddr[:], McNwkSKey: mg.MCNwkSKey[:], FCnt: mg.FCnt, Dr: uint32(mg.DR), Frequency: uint32(mg.Frequency), PingSlotPeriod: uint32(mg.PingSlotPeriod), ServiceProfileId: mg.ServiceProfileID.Bytes(), RoutingProfileId: mg.RoutingProfileID.Bytes(), }, } switch mg.GroupType { case storage.MulticastGroupB: resp.MulticastGroup.GroupType = ns.MulticastGroupType_CLASS_B case storage.MulticastGroupC: resp.MulticastGroup.GroupType = ns.MulticastGroupType_CLASS_C default: return nil, grpc.Errorf(codes.Internal, "invalid group-type: %s", mg.GroupType) } resp.CreatedAt, err = ptypes.TimestampProto(mg.CreatedAt) if err != nil { return nil, errToRPCError(err) } resp.UpdatedAt, err = ptypes.TimestampProto(mg.UpdatedAt) if err != nil { return nil, errToRPCError(err) } return &resp, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "GetMulticastGroup", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "GetMulticastGroupRequest", ")", "(", "*", "ns", ".", "GetMulticastGroupResponse", ",", "error", ")", "{", "var", "mgID", "uuid", ".", "UUID", "\n", "copy", "(", "mgID", "[", ":", "]", ",", "req", ".", "Id", ")", "\n\n", "mg", ",", "err", ":=", "storage", ".", "GetMulticastGroup", "(", "storage", ".", "DB", "(", ")", ",", "mgID", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "resp", ":=", "ns", ".", "GetMulticastGroupResponse", "{", "MulticastGroup", ":", "&", "ns", ".", "MulticastGroup", "{", "Id", ":", "mg", ".", "ID", ".", "Bytes", "(", ")", ",", "McAddr", ":", "mg", ".", "MCAddr", "[", ":", "]", ",", "McNwkSKey", ":", "mg", ".", "MCNwkSKey", "[", ":", "]", ",", "FCnt", ":", "mg", ".", "FCnt", ",", "Dr", ":", "uint32", "(", "mg", ".", "DR", ")", ",", "Frequency", ":", "uint32", "(", "mg", ".", "Frequency", ")", ",", "PingSlotPeriod", ":", "uint32", "(", "mg", ".", "PingSlotPeriod", ")", ",", "ServiceProfileId", ":", "mg", ".", "ServiceProfileID", ".", "Bytes", "(", ")", ",", "RoutingProfileId", ":", "mg", ".", "RoutingProfileID", ".", "Bytes", "(", ")", ",", "}", ",", "}", "\n\n", "switch", "mg", ".", "GroupType", "{", "case", "storage", ".", "MulticastGroupB", ":", "resp", ".", "MulticastGroup", ".", "GroupType", "=", "ns", ".", "MulticastGroupType_CLASS_B", "\n", "case", "storage", ".", "MulticastGroupC", ":", "resp", ".", "MulticastGroup", ".", "GroupType", "=", "ns", ".", "MulticastGroupType_CLASS_C", "\n", "default", ":", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ",", "mg", ".", "GroupType", ")", "\n", "}", "\n\n", "resp", ".", "CreatedAt", ",", "err", "=", "ptypes", ".", "TimestampProto", "(", "mg", ".", "CreatedAt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "resp", ".", "UpdatedAt", ",", "err", "=", "ptypes", ".", "TimestampProto", "(", "mg", ".", "UpdatedAt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "resp", ",", "nil", "\n", "}" ]
// GetMulticastGroup returns the multicast-group given an id.
[ "GetMulticastGroup", "returns", "the", "multicast", "-", "group", "given", "an", "id", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1469-L1512
train
brocaar/loraserver
internal/api/network_server.go
UpdateMulticastGroup
func (n *NetworkServerAPI) UpdateMulticastGroup(ctx context.Context, req *ns.UpdateMulticastGroupRequest) (*empty.Empty, error) { if req.MulticastGroup == nil { return nil, grpc.Errorf(codes.InvalidArgument, "multicast_group must not be nil") } var mgID uuid.UUID copy(mgID[:], req.MulticastGroup.Id) err := storage.Transaction(func(tx sqlx.Ext) error { mg, err := storage.GetMulticastGroup(tx, mgID, true) if err != nil { return errToRPCError(err) } copy(mg.MCAddr[:], req.MulticastGroup.McAddr) copy(mg.MCNwkSKey[:], req.MulticastGroup.McNwkSKey) copy(mg.ServiceProfileID[:], req.MulticastGroup.ServiceProfileId) copy(mg.RoutingProfileID[:], req.MulticastGroup.RoutingProfileId) mg.FCnt = req.MulticastGroup.FCnt mg.DR = int(req.MulticastGroup.Dr) mg.Frequency = int(req.MulticastGroup.Frequency) mg.PingSlotPeriod = int(req.MulticastGroup.PingSlotPeriod) switch req.MulticastGroup.GroupType { case ns.MulticastGroupType_CLASS_B: mg.GroupType = storage.MulticastGroupB case ns.MulticastGroupType_CLASS_C: mg.GroupType = storage.MulticastGroupC default: return grpc.Errorf(codes.InvalidArgument, "invalid group_type") } if err := storage.UpdateMulticastGroup(tx, &mg); err != nil { return errToRPCError(err) } return nil }) if err != nil { return nil, err } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) UpdateMulticastGroup(ctx context.Context, req *ns.UpdateMulticastGroupRequest) (*empty.Empty, error) { if req.MulticastGroup == nil { return nil, grpc.Errorf(codes.InvalidArgument, "multicast_group must not be nil") } var mgID uuid.UUID copy(mgID[:], req.MulticastGroup.Id) err := storage.Transaction(func(tx sqlx.Ext) error { mg, err := storage.GetMulticastGroup(tx, mgID, true) if err != nil { return errToRPCError(err) } copy(mg.MCAddr[:], req.MulticastGroup.McAddr) copy(mg.MCNwkSKey[:], req.MulticastGroup.McNwkSKey) copy(mg.ServiceProfileID[:], req.MulticastGroup.ServiceProfileId) copy(mg.RoutingProfileID[:], req.MulticastGroup.RoutingProfileId) mg.FCnt = req.MulticastGroup.FCnt mg.DR = int(req.MulticastGroup.Dr) mg.Frequency = int(req.MulticastGroup.Frequency) mg.PingSlotPeriod = int(req.MulticastGroup.PingSlotPeriod) switch req.MulticastGroup.GroupType { case ns.MulticastGroupType_CLASS_B: mg.GroupType = storage.MulticastGroupB case ns.MulticastGroupType_CLASS_C: mg.GroupType = storage.MulticastGroupC default: return grpc.Errorf(codes.InvalidArgument, "invalid group_type") } if err := storage.UpdateMulticastGroup(tx, &mg); err != nil { return errToRPCError(err) } return nil }) if err != nil { return nil, err } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "UpdateMulticastGroup", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "UpdateMulticastGroupRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "if", "req", ".", "MulticastGroup", "==", "nil", "{", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "mgID", "uuid", ".", "UUID", "\n", "copy", "(", "mgID", "[", ":", "]", ",", "req", ".", "MulticastGroup", ".", "Id", ")", "\n\n", "err", ":=", "storage", ".", "Transaction", "(", "func", "(", "tx", "sqlx", ".", "Ext", ")", "error", "{", "mg", ",", "err", ":=", "storage", ".", "GetMulticastGroup", "(", "tx", ",", "mgID", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "copy", "(", "mg", ".", "MCAddr", "[", ":", "]", ",", "req", ".", "MulticastGroup", ".", "McAddr", ")", "\n", "copy", "(", "mg", ".", "MCNwkSKey", "[", ":", "]", ",", "req", ".", "MulticastGroup", ".", "McNwkSKey", ")", "\n", "copy", "(", "mg", ".", "ServiceProfileID", "[", ":", "]", ",", "req", ".", "MulticastGroup", ".", "ServiceProfileId", ")", "\n", "copy", "(", "mg", ".", "RoutingProfileID", "[", ":", "]", ",", "req", ".", "MulticastGroup", ".", "RoutingProfileId", ")", "\n", "mg", ".", "FCnt", "=", "req", ".", "MulticastGroup", ".", "FCnt", "\n", "mg", ".", "DR", "=", "int", "(", "req", ".", "MulticastGroup", ".", "Dr", ")", "\n", "mg", ".", "Frequency", "=", "int", "(", "req", ".", "MulticastGroup", ".", "Frequency", ")", "\n", "mg", ".", "PingSlotPeriod", "=", "int", "(", "req", ".", "MulticastGroup", ".", "PingSlotPeriod", ")", "\n\n", "switch", "req", ".", "MulticastGroup", ".", "GroupType", "{", "case", "ns", ".", "MulticastGroupType_CLASS_B", ":", "mg", ".", "GroupType", "=", "storage", ".", "MulticastGroupB", "\n", "case", "ns", ".", "MulticastGroupType_CLASS_C", ":", "mg", ".", "GroupType", "=", "storage", ".", "MulticastGroupC", "\n", "default", ":", "return", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "storage", ".", "UpdateMulticastGroup", "(", "tx", ",", "&", "mg", ")", ";", "err", "!=", "nil", "{", "return", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// UpdateMulticastGroup updates the given multicast-group.
[ "UpdateMulticastGroup", "updates", "the", "given", "multicast", "-", "group", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1515-L1558
train
brocaar/loraserver
internal/api/network_server.go
DeleteMulticastGroup
func (n *NetworkServerAPI) DeleteMulticastGroup(ctx context.Context, req *ns.DeleteMulticastGroupRequest) (*empty.Empty, error) { var mgID uuid.UUID copy(mgID[:], req.Id) if err := storage.DeleteMulticastGroup(storage.DB(), mgID); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) DeleteMulticastGroup(ctx context.Context, req *ns.DeleteMulticastGroupRequest) (*empty.Empty, error) { var mgID uuid.UUID copy(mgID[:], req.Id) if err := storage.DeleteMulticastGroup(storage.DB(), mgID); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "DeleteMulticastGroup", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "DeleteMulticastGroupRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "var", "mgID", "uuid", ".", "UUID", "\n", "copy", "(", "mgID", "[", ":", "]", ",", "req", ".", "Id", ")", "\n\n", "if", "err", ":=", "storage", ".", "DeleteMulticastGroup", "(", "storage", ".", "DB", "(", ")", ",", "mgID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// DeleteMulticastGroup deletes a multicast-group given an id.
[ "DeleteMulticastGroup", "deletes", "a", "multicast", "-", "group", "given", "an", "id", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1561-L1570
train
brocaar/loraserver
internal/api/network_server.go
EnqueueMulticastQueueItem
func (n *NetworkServerAPI) EnqueueMulticastQueueItem(ctx context.Context, req *ns.EnqueueMulticastQueueItemRequest) (*empty.Empty, error) { if req.MulticastQueueItem == nil { return nil, grpc.Errorf(codes.InvalidArgument, "multicast_queue_item must not be nil") } var mgID uuid.UUID copy(mgID[:], req.MulticastQueueItem.MulticastGroupId) qi := storage.MulticastQueueItem{ MulticastGroupID: mgID, FCnt: req.MulticastQueueItem.FCnt, FPort: uint8(req.MulticastQueueItem.FPort), FRMPayload: req.MulticastQueueItem.FrmPayload, } err := storage.Transaction(func(tx sqlx.Ext) error { return multicast.EnqueueQueueItem(storage.RedisPool(), tx, qi) }) if err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) EnqueueMulticastQueueItem(ctx context.Context, req *ns.EnqueueMulticastQueueItemRequest) (*empty.Empty, error) { if req.MulticastQueueItem == nil { return nil, grpc.Errorf(codes.InvalidArgument, "multicast_queue_item must not be nil") } var mgID uuid.UUID copy(mgID[:], req.MulticastQueueItem.MulticastGroupId) qi := storage.MulticastQueueItem{ MulticastGroupID: mgID, FCnt: req.MulticastQueueItem.FCnt, FPort: uint8(req.MulticastQueueItem.FPort), FRMPayload: req.MulticastQueueItem.FrmPayload, } err := storage.Transaction(func(tx sqlx.Ext) error { return multicast.EnqueueQueueItem(storage.RedisPool(), tx, qi) }) if err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "EnqueueMulticastQueueItem", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "EnqueueMulticastQueueItemRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "if", "req", ".", "MulticastQueueItem", "==", "nil", "{", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "mgID", "uuid", ".", "UUID", "\n", "copy", "(", "mgID", "[", ":", "]", ",", "req", ".", "MulticastQueueItem", ".", "MulticastGroupId", ")", "\n\n", "qi", ":=", "storage", ".", "MulticastQueueItem", "{", "MulticastGroupID", ":", "mgID", ",", "FCnt", ":", "req", ".", "MulticastQueueItem", ".", "FCnt", ",", "FPort", ":", "uint8", "(", "req", ".", "MulticastQueueItem", ".", "FPort", ")", ",", "FRMPayload", ":", "req", ".", "MulticastQueueItem", ".", "FrmPayload", ",", "}", "\n\n", "err", ":=", "storage", ".", "Transaction", "(", "func", "(", "tx", "sqlx", ".", "Ext", ")", "error", "{", "return", "multicast", ".", "EnqueueQueueItem", "(", "storage", ".", "RedisPool", "(", ")", ",", "tx", ",", "qi", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// EnqueueMulticastQueueItem creates the given multicast queue-item.
[ "EnqueueMulticastQueueItem", "creates", "the", "given", "multicast", "queue", "-", "item", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1601-L1624
train
brocaar/loraserver
internal/api/network_server.go
FlushMulticastQueueForMulticastGroup
func (n *NetworkServerAPI) FlushMulticastQueueForMulticastGroup(ctx context.Context, req *ns.FlushMulticastQueueForMulticastGroupRequest) (*empty.Empty, error) { var mgID uuid.UUID copy(mgID[:], req.MulticastGroupId) if err := storage.FlushMulticastQueueForMulticastGroup(storage.DB(), mgID); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
go
func (n *NetworkServerAPI) FlushMulticastQueueForMulticastGroup(ctx context.Context, req *ns.FlushMulticastQueueForMulticastGroupRequest) (*empty.Empty, error) { var mgID uuid.UUID copy(mgID[:], req.MulticastGroupId) if err := storage.FlushMulticastQueueForMulticastGroup(storage.DB(), mgID); err != nil { return nil, errToRPCError(err) } return &empty.Empty{}, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "FlushMulticastQueueForMulticastGroup", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "FlushMulticastQueueForMulticastGroupRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "var", "mgID", "uuid", ".", "UUID", "\n", "copy", "(", "mgID", "[", ":", "]", ",", "req", ".", "MulticastGroupId", ")", "\n\n", "if", "err", ":=", "storage", ".", "FlushMulticastQueueForMulticastGroup", "(", "storage", ".", "DB", "(", ")", ",", "mgID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// FlushMulticastQueueForMulticastGroup flushes the multicast device-queue given a multicast-group id.
[ "FlushMulticastQueueForMulticastGroup", "flushes", "the", "multicast", "device", "-", "queue", "given", "a", "multicast", "-", "group", "id", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1627-L1636
train
brocaar/loraserver
internal/api/network_server.go
GetMulticastQueueItemsForMulticastGroup
func (n *NetworkServerAPI) GetMulticastQueueItemsForMulticastGroup(ctx context.Context, req *ns.GetMulticastQueueItemsForMulticastGroupRequest) (*ns.GetMulticastQueueItemsForMulticastGroupResponse, error) { var mgID uuid.UUID copy(mgID[:], req.MulticastGroupId) items, err := storage.GetMulticastQueueItemsForMulticastGroup(storage.DB(), mgID) if err != nil { return nil, errToRPCError(err) } counterSeen := make(map[uint32]struct{}) var out ns.GetMulticastQueueItemsForMulticastGroupResponse for i := range items { // we need to de-duplicate the queue-items as they are created per-gateway if _, seen := counterSeen[items[i].FCnt]; seen { continue } qi := ns.MulticastQueueItem{ MulticastGroupId: items[i].MulticastGroupID.Bytes(), FrmPayload: items[i].FRMPayload, FCnt: items[i].FCnt, FPort: uint32(items[i].FPort), } counterSeen[items[i].FCnt] = struct{}{} out.MulticastQueueItems = append(out.MulticastQueueItems, &qi) } return &out, nil }
go
func (n *NetworkServerAPI) GetMulticastQueueItemsForMulticastGroup(ctx context.Context, req *ns.GetMulticastQueueItemsForMulticastGroupRequest) (*ns.GetMulticastQueueItemsForMulticastGroupResponse, error) { var mgID uuid.UUID copy(mgID[:], req.MulticastGroupId) items, err := storage.GetMulticastQueueItemsForMulticastGroup(storage.DB(), mgID) if err != nil { return nil, errToRPCError(err) } counterSeen := make(map[uint32]struct{}) var out ns.GetMulticastQueueItemsForMulticastGroupResponse for i := range items { // we need to de-duplicate the queue-items as they are created per-gateway if _, seen := counterSeen[items[i].FCnt]; seen { continue } qi := ns.MulticastQueueItem{ MulticastGroupId: items[i].MulticastGroupID.Bytes(), FrmPayload: items[i].FRMPayload, FCnt: items[i].FCnt, FPort: uint32(items[i].FPort), } counterSeen[items[i].FCnt] = struct{}{} out.MulticastQueueItems = append(out.MulticastQueueItems, &qi) } return &out, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "GetMulticastQueueItemsForMulticastGroup", "(", "ctx", "context", ".", "Context", ",", "req", "*", "ns", ".", "GetMulticastQueueItemsForMulticastGroupRequest", ")", "(", "*", "ns", ".", "GetMulticastQueueItemsForMulticastGroupResponse", ",", "error", ")", "{", "var", "mgID", "uuid", ".", "UUID", "\n", "copy", "(", "mgID", "[", ":", "]", ",", "req", ".", "MulticastGroupId", ")", "\n\n", "items", ",", "err", ":=", "storage", ".", "GetMulticastQueueItemsForMulticastGroup", "(", "storage", ".", "DB", "(", ")", ",", "mgID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errToRPCError", "(", "err", ")", "\n", "}", "\n\n", "counterSeen", ":=", "make", "(", "map", "[", "uint32", "]", "struct", "{", "}", ")", "\n", "var", "out", "ns", ".", "GetMulticastQueueItemsForMulticastGroupResponse", "\n", "for", "i", ":=", "range", "items", "{", "// we need to de-duplicate the queue-items as they are created per-gateway", "if", "_", ",", "seen", ":=", "counterSeen", "[", "items", "[", "i", "]", ".", "FCnt", "]", ";", "seen", "{", "continue", "\n", "}", "\n\n", "qi", ":=", "ns", ".", "MulticastQueueItem", "{", "MulticastGroupId", ":", "items", "[", "i", "]", ".", "MulticastGroupID", ".", "Bytes", "(", ")", ",", "FrmPayload", ":", "items", "[", "i", "]", ".", "FRMPayload", ",", "FCnt", ":", "items", "[", "i", "]", ".", "FCnt", ",", "FPort", ":", "uint32", "(", "items", "[", "i", "]", ".", "FPort", ")", ",", "}", "\n", "counterSeen", "[", "items", "[", "i", "]", ".", "FCnt", "]", "=", "struct", "{", "}", "{", "}", "\n", "out", ".", "MulticastQueueItems", "=", "append", "(", "out", ".", "MulticastQueueItems", ",", "&", "qi", ")", "\n", "}", "\n\n", "return", "&", "out", ",", "nil", "\n", "}" ]
// GetMulticastQueueItemsForMulticastGroup returns the queue-items given a multicast-group id.
[ "GetMulticastQueueItemsForMulticastGroup", "returns", "the", "queue", "-", "items", "given", "a", "multicast", "-", "group", "id", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1639-L1667
train
brocaar/loraserver
internal/api/network_server.go
GetVersion
func (n *NetworkServerAPI) GetVersion(ctx context.Context, req *empty.Empty) (*ns.GetVersionResponse, error) { region, ok := map[string]common.Region{ common.Region_AS923.String(): common.Region_AS923, common.Region_AU915.String(): common.Region_AU915, common.Region_CN470.String(): common.Region_CN470, common.Region_CN779.String(): common.Region_CN779, common.Region_EU433.String(): common.Region_EU433, common.Region_EU868.String(): common.Region_EU868, common.Region_IN865.String(): common.Region_IN865, common.Region_KR920.String(): common.Region_KR920, common.Region_RU864.String(): common.Region_RU864, common.Region_US915.String(): common.Region_US915, }[band.Band().Name()] if !ok { log.WithFields(log.Fields{ "band_name": band.Band().Name(), }).Warning("unknown band to common name mapping") } return &ns.GetVersionResponse{ Region: region, Version: config.Version, }, nil }
go
func (n *NetworkServerAPI) GetVersion(ctx context.Context, req *empty.Empty) (*ns.GetVersionResponse, error) { region, ok := map[string]common.Region{ common.Region_AS923.String(): common.Region_AS923, common.Region_AU915.String(): common.Region_AU915, common.Region_CN470.String(): common.Region_CN470, common.Region_CN779.String(): common.Region_CN779, common.Region_EU433.String(): common.Region_EU433, common.Region_EU868.String(): common.Region_EU868, common.Region_IN865.String(): common.Region_IN865, common.Region_KR920.String(): common.Region_KR920, common.Region_RU864.String(): common.Region_RU864, common.Region_US915.String(): common.Region_US915, }[band.Band().Name()] if !ok { log.WithFields(log.Fields{ "band_name": band.Band().Name(), }).Warning("unknown band to common name mapping") } return &ns.GetVersionResponse{ Region: region, Version: config.Version, }, nil }
[ "func", "(", "n", "*", "NetworkServerAPI", ")", "GetVersion", "(", "ctx", "context", ".", "Context", ",", "req", "*", "empty", ".", "Empty", ")", "(", "*", "ns", ".", "GetVersionResponse", ",", "error", ")", "{", "region", ",", "ok", ":=", "map", "[", "string", "]", "common", ".", "Region", "{", "common", ".", "Region_AS923", ".", "String", "(", ")", ":", "common", ".", "Region_AS923", ",", "common", ".", "Region_AU915", ".", "String", "(", ")", ":", "common", ".", "Region_AU915", ",", "common", ".", "Region_CN470", ".", "String", "(", ")", ":", "common", ".", "Region_CN470", ",", "common", ".", "Region_CN779", ".", "String", "(", ")", ":", "common", ".", "Region_CN779", ",", "common", ".", "Region_EU433", ".", "String", "(", ")", ":", "common", ".", "Region_EU433", ",", "common", ".", "Region_EU868", ".", "String", "(", ")", ":", "common", ".", "Region_EU868", ",", "common", ".", "Region_IN865", ".", "String", "(", ")", ":", "common", ".", "Region_IN865", ",", "common", ".", "Region_KR920", ".", "String", "(", ")", ":", "common", ".", "Region_KR920", ",", "common", ".", "Region_RU864", ".", "String", "(", ")", ":", "common", ".", "Region_RU864", ",", "common", ".", "Region_US915", ".", "String", "(", ")", ":", "common", ".", "Region_US915", ",", "}", "[", "band", ".", "Band", "(", ")", ".", "Name", "(", ")", "]", "\n\n", "if", "!", "ok", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "band", ".", "Band", "(", ")", ".", "Name", "(", ")", ",", "}", ")", ".", "Warning", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "ns", ".", "GetVersionResponse", "{", "Region", ":", "region", ",", "Version", ":", "config", ".", "Version", ",", "}", ",", "nil", "\n", "}" ]
// GetVersion returns the LoRa Server version.
[ "GetVersion", "returns", "the", "LoRa", "Server", "version", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/api/network_server.go#L1670-L1694
train
brocaar/loraserver
internal/framelog/helpers.go
CreateUplinkFrameSet
func CreateUplinkFrameSet(rxPacket models.RXPacket) (gw.UplinkFrameSet, error) { b, err := rxPacket.PHYPayload.MarshalBinary() if err != nil { return gw.UplinkFrameSet{}, errors.Wrap(err, "marshal phypayload error") } return gw.UplinkFrameSet{ PhyPayload: b, TxInfo: rxPacket.TXInfo, RxInfo: rxPacket.RXInfoSet, }, nil }
go
func CreateUplinkFrameSet(rxPacket models.RXPacket) (gw.UplinkFrameSet, error) { b, err := rxPacket.PHYPayload.MarshalBinary() if err != nil { return gw.UplinkFrameSet{}, errors.Wrap(err, "marshal phypayload error") } return gw.UplinkFrameSet{ PhyPayload: b, TxInfo: rxPacket.TXInfo, RxInfo: rxPacket.RXInfoSet, }, nil }
[ "func", "CreateUplinkFrameSet", "(", "rxPacket", "models", ".", "RXPacket", ")", "(", "gw", ".", "UplinkFrameSet", ",", "error", ")", "{", "b", ",", "err", ":=", "rxPacket", ".", "PHYPayload", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "gw", ".", "UplinkFrameSet", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "gw", ".", "UplinkFrameSet", "{", "PhyPayload", ":", "b", ",", "TxInfo", ":", "rxPacket", ".", "TXInfo", ",", "RxInfo", ":", "rxPacket", ".", "RXInfoSet", ",", "}", ",", "nil", "\n", "}" ]
// CreateUplinkFrameSet creates a UplinkFrameSet.
[ "CreateUplinkFrameSet", "creates", "a", "UplinkFrameSet", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/framelog/helpers.go#L11-L22
train
brocaar/loraserver
internal/backend/joinserver/pool.go
Get
func (p *pool) Get(joinEUI lorawan.EUI64) (Client, error) { if !p.resolveJoinEUI { return p.defaultClient, nil } p.RLock() pc, ok := p.clients[joinEUI] p.RUnlock() if ok { return pc.client, nil } client, err := p.resolveJoinServer(joinEUI) if err != nil { log.WithField("join_eui", joinEUI).WithError(err).Warning("resolving JoinEUI failed, using default join-server") return p.defaultClient, nil } p.Lock() p.clients[joinEUI] = poolClient{client: client} p.Unlock() return client, nil }
go
func (p *pool) Get(joinEUI lorawan.EUI64) (Client, error) { if !p.resolveJoinEUI { return p.defaultClient, nil } p.RLock() pc, ok := p.clients[joinEUI] p.RUnlock() if ok { return pc.client, nil } client, err := p.resolveJoinServer(joinEUI) if err != nil { log.WithField("join_eui", joinEUI).WithError(err).Warning("resolving JoinEUI failed, using default join-server") return p.defaultClient, nil } p.Lock() p.clients[joinEUI] = poolClient{client: client} p.Unlock() return client, nil }
[ "func", "(", "p", "*", "pool", ")", "Get", "(", "joinEUI", "lorawan", ".", "EUI64", ")", "(", "Client", ",", "error", ")", "{", "if", "!", "p", ".", "resolveJoinEUI", "{", "return", "p", ".", "defaultClient", ",", "nil", "\n", "}", "\n\n", "p", ".", "RLock", "(", ")", "\n", "pc", ",", "ok", ":=", "p", ".", "clients", "[", "joinEUI", "]", "\n", "p", ".", "RUnlock", "(", ")", "\n", "if", "ok", "{", "return", "pc", ".", "client", ",", "nil", "\n", "}", "\n\n", "client", ",", "err", ":=", "p", ".", "resolveJoinServer", "(", "joinEUI", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithField", "(", "\"", "\"", ",", "joinEUI", ")", ".", "WithError", "(", "err", ")", ".", "Warning", "(", "\"", "\"", ")", "\n", "return", "p", ".", "defaultClient", ",", "nil", "\n", "}", "\n\n", "p", ".", "Lock", "(", ")", "\n", "p", ".", "clients", "[", "joinEUI", "]", "=", "poolClient", "{", "client", ":", "client", "}", "\n", "p", ".", "Unlock", "(", ")", "\n\n", "return", "client", ",", "nil", "\n", "}" ]
// Get returns the join-server client for the given joinEUI.
[ "Get", "returns", "the", "join", "-", "server", "client", "for", "the", "given", "joinEUI", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/joinserver/pool.go#L41-L64
train
brocaar/loraserver
cmd/loraserver/cmd/mqtt2to3.go
NewMQTT2To3Backend
func NewMQTT2To3Backend(conf config.Config) (*MQTT2To3Backend, error) { c := conf.NetworkServer.Gateway.Backend.MQTT b := MQTT2To3Backend{} opts := mqtt.NewClientOptions() opts.AddBroker(c.Server) opts.SetUsername(c.Username) opts.SetPassword(c.Password) opts.SetCleanSession(c.CleanSession) opts.SetClientID(c.ClientID) opts.SetOnConnectHandler(b.onConnected) tlsconfig, err := newTLSConfig(c.CACert, c.TLSCert, c.TLSKey) if err != nil { log.WithError(err).WithFields(log.Fields{ "ca_cert": c.CACert, "tls_cert": c.TLSCert, "tls_key": c.TLSKey, }).Fatal("mqtt2to3: error loading mqtt certificate files") } if tlsconfig != nil { opts.SetTLSConfig(tlsconfig) } log.WithField("broker", c.Server).Info("mqtt2to3: connecting to mqtt broker") b.conn = mqtt.NewClient(opts) for { if token := b.conn.Connect(); token.Wait() && token.Error() != nil { log.WithError(err).Error("mqtt2to3: connecting to mqtt broker failed") time.Sleep(2 * time.Second) } else { break } } return &b, nil }
go
func NewMQTT2To3Backend(conf config.Config) (*MQTT2To3Backend, error) { c := conf.NetworkServer.Gateway.Backend.MQTT b := MQTT2To3Backend{} opts := mqtt.NewClientOptions() opts.AddBroker(c.Server) opts.SetUsername(c.Username) opts.SetPassword(c.Password) opts.SetCleanSession(c.CleanSession) opts.SetClientID(c.ClientID) opts.SetOnConnectHandler(b.onConnected) tlsconfig, err := newTLSConfig(c.CACert, c.TLSCert, c.TLSKey) if err != nil { log.WithError(err).WithFields(log.Fields{ "ca_cert": c.CACert, "tls_cert": c.TLSCert, "tls_key": c.TLSKey, }).Fatal("mqtt2to3: error loading mqtt certificate files") } if tlsconfig != nil { opts.SetTLSConfig(tlsconfig) } log.WithField("broker", c.Server).Info("mqtt2to3: connecting to mqtt broker") b.conn = mqtt.NewClient(opts) for { if token := b.conn.Connect(); token.Wait() && token.Error() != nil { log.WithError(err).Error("mqtt2to3: connecting to mqtt broker failed") time.Sleep(2 * time.Second) } else { break } } return &b, nil }
[ "func", "NewMQTT2To3Backend", "(", "conf", "config", ".", "Config", ")", "(", "*", "MQTT2To3Backend", ",", "error", ")", "{", "c", ":=", "conf", ".", "NetworkServer", ".", "Gateway", ".", "Backend", ".", "MQTT", "\n\n", "b", ":=", "MQTT2To3Backend", "{", "}", "\n\n", "opts", ":=", "mqtt", ".", "NewClientOptions", "(", ")", "\n", "opts", ".", "AddBroker", "(", "c", ".", "Server", ")", "\n", "opts", ".", "SetUsername", "(", "c", ".", "Username", ")", "\n", "opts", ".", "SetPassword", "(", "c", ".", "Password", ")", "\n", "opts", ".", "SetCleanSession", "(", "c", ".", "CleanSession", ")", "\n", "opts", ".", "SetClientID", "(", "c", ".", "ClientID", ")", "\n", "opts", ".", "SetOnConnectHandler", "(", "b", ".", "onConnected", ")", "\n\n", "tlsconfig", ",", "err", ":=", "newTLSConfig", "(", "c", ".", "CACert", ",", "c", ".", "TLSCert", ",", "c", ".", "TLSKey", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "c", ".", "CACert", ",", "\"", "\"", ":", "c", ".", "TLSCert", ",", "\"", "\"", ":", "c", ".", "TLSKey", ",", "}", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "tlsconfig", "!=", "nil", "{", "opts", ".", "SetTLSConfig", "(", "tlsconfig", ")", "\n", "}", "\n\n", "log", ".", "WithField", "(", "\"", "\"", ",", "c", ".", "Server", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "b", ".", "conn", "=", "mqtt", ".", "NewClient", "(", "opts", ")", "\n\n", "for", "{", "if", "token", ":=", "b", ".", "conn", ".", "Connect", "(", ")", ";", "token", ".", "Wait", "(", ")", "&&", "token", ".", "Error", "(", ")", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "time", ".", "Sleep", "(", "2", "*", "time", ".", "Second", ")", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "&", "b", ",", "nil", "\n", "}" ]
// NewMQTT2To3Backend creates a new Backend.
[ "NewMQTT2To3Backend", "creates", "a", "new", "Backend", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/cmd/loraserver/cmd/mqtt2to3.go#L43-L81
train
brocaar/loraserver
internal/storage/downlink_frames.go
SaveDownlinkFrames
func SaveDownlinkFrames(p *redis.Pool, devEUI lorawan.EUI64, frames []gw.DownlinkFrame) error { if len(frames) == 0 { return nil } var token uint32 var frameBytes [][]byte for _, frame := range frames { token = frame.Token b, err := proto.Marshal(&frame) if err != nil { return errors.Wrap(err, "marshal proto error") } frameBytes = append(frameBytes, b) } c := p.Get() defer c.Close() exp := int64(downlinkFramesTTL) / int64(time.Millisecond) c.Send("MULTI") // store frames key := fmt.Sprintf(downlinkFramesKeyTempl, token) for i := range frameBytes { c.Send("RPUSH", key, frameBytes[i]) } c.Send("PEXPIRE", key, exp) // store pointer to deveui key = fmt.Sprintf(downlinkFramesDevEUIKeyTempl, token) c.Send("PSETEX", key, exp, devEUI[:]) // execute if _, err := c.Do("EXEC"); err != nil { return errors.Wrap(err, "exec error") } log.WithFields(log.Fields{ "token": token, "dev_eui": devEUI, }).Info("downlink-frames saved") return nil }
go
func SaveDownlinkFrames(p *redis.Pool, devEUI lorawan.EUI64, frames []gw.DownlinkFrame) error { if len(frames) == 0 { return nil } var token uint32 var frameBytes [][]byte for _, frame := range frames { token = frame.Token b, err := proto.Marshal(&frame) if err != nil { return errors.Wrap(err, "marshal proto error") } frameBytes = append(frameBytes, b) } c := p.Get() defer c.Close() exp := int64(downlinkFramesTTL) / int64(time.Millisecond) c.Send("MULTI") // store frames key := fmt.Sprintf(downlinkFramesKeyTempl, token) for i := range frameBytes { c.Send("RPUSH", key, frameBytes[i]) } c.Send("PEXPIRE", key, exp) // store pointer to deveui key = fmt.Sprintf(downlinkFramesDevEUIKeyTempl, token) c.Send("PSETEX", key, exp, devEUI[:]) // execute if _, err := c.Do("EXEC"); err != nil { return errors.Wrap(err, "exec error") } log.WithFields(log.Fields{ "token": token, "dev_eui": devEUI, }).Info("downlink-frames saved") return nil }
[ "func", "SaveDownlinkFrames", "(", "p", "*", "redis", ".", "Pool", ",", "devEUI", "lorawan", ".", "EUI64", ",", "frames", "[", "]", "gw", ".", "DownlinkFrame", ")", "error", "{", "if", "len", "(", "frames", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "var", "token", "uint32", "\n", "var", "frameBytes", "[", "]", "[", "]", "byte", "\n", "for", "_", ",", "frame", ":=", "range", "frames", "{", "token", "=", "frame", ".", "Token", "\n", "b", ",", "err", ":=", "proto", ".", "Marshal", "(", "&", "frame", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "frameBytes", "=", "append", "(", "frameBytes", ",", "b", ")", "\n", "}", "\n\n", "c", ":=", "p", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n\n", "exp", ":=", "int64", "(", "downlinkFramesTTL", ")", "/", "int64", "(", "time", ".", "Millisecond", ")", "\n", "c", ".", "Send", "(", "\"", "\"", ")", "\n\n", "// store frames", "key", ":=", "fmt", ".", "Sprintf", "(", "downlinkFramesKeyTempl", ",", "token", ")", "\n", "for", "i", ":=", "range", "frameBytes", "{", "c", ".", "Send", "(", "\"", "\"", ",", "key", ",", "frameBytes", "[", "i", "]", ")", "\n", "}", "\n", "c", ".", "Send", "(", "\"", "\"", ",", "key", ",", "exp", ")", "\n\n", "// store pointer to deveui", "key", "=", "fmt", ".", "Sprintf", "(", "downlinkFramesDevEUIKeyTempl", ",", "token", ")", "\n", "c", ".", "Send", "(", "\"", "\"", ",", "key", ",", "exp", ",", "devEUI", "[", ":", "]", ")", "\n\n", "// execute", "if", "_", ",", "err", ":=", "c", ".", "Do", "(", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "token", ",", "\"", "\"", ":", "devEUI", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n\n", "return", "nil", "\n", "}" ]
// SaveDownlinkFrames saves the given downlink-frames. The downlink-frames // must share the same token!
[ "SaveDownlinkFrames", "saves", "the", "given", "downlink", "-", "frames", ".", "The", "downlink", "-", "frames", "must", "share", "the", "same", "token!" ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/downlink_frames.go#L22-L66
train
brocaar/loraserver
internal/storage/downlink_frames.go
PopDownlinkFrame
func PopDownlinkFrame(p *redis.Pool, token uint32) (lorawan.EUI64, gw.DownlinkFrame, error) { var out gw.DownlinkFrame var devEUI lorawan.EUI64 c := p.Get() defer c.Close() b, err := redis.Bytes(c.Do("LPOP", fmt.Sprintf(downlinkFramesKeyTempl, token))) if err != nil { if err == redis.ErrNil { return lorawan.EUI64{}, gw.DownlinkFrame{}, ErrDoesNotExist } return lorawan.EUI64{}, gw.DownlinkFrame{}, errors.Wrap(err, "lpop error") } err = proto.Unmarshal(b, &out) if err != nil { return lorawan.EUI64{}, gw.DownlinkFrame{}, errors.Wrap(err, "proto unmarshal error") } b, err = redis.Bytes(c.Do("GET", fmt.Sprintf(downlinkFramesDevEUIKeyTempl, token))) if err != nil { if err == redis.ErrNil { return lorawan.EUI64{}, gw.DownlinkFrame{}, ErrDoesNotExist } return lorawan.EUI64{}, gw.DownlinkFrame{}, errors.Wrap(err, "get error") } copy(devEUI[:], b) return devEUI, out, nil }
go
func PopDownlinkFrame(p *redis.Pool, token uint32) (lorawan.EUI64, gw.DownlinkFrame, error) { var out gw.DownlinkFrame var devEUI lorawan.EUI64 c := p.Get() defer c.Close() b, err := redis.Bytes(c.Do("LPOP", fmt.Sprintf(downlinkFramesKeyTempl, token))) if err != nil { if err == redis.ErrNil { return lorawan.EUI64{}, gw.DownlinkFrame{}, ErrDoesNotExist } return lorawan.EUI64{}, gw.DownlinkFrame{}, errors.Wrap(err, "lpop error") } err = proto.Unmarshal(b, &out) if err != nil { return lorawan.EUI64{}, gw.DownlinkFrame{}, errors.Wrap(err, "proto unmarshal error") } b, err = redis.Bytes(c.Do("GET", fmt.Sprintf(downlinkFramesDevEUIKeyTempl, token))) if err != nil { if err == redis.ErrNil { return lorawan.EUI64{}, gw.DownlinkFrame{}, ErrDoesNotExist } return lorawan.EUI64{}, gw.DownlinkFrame{}, errors.Wrap(err, "get error") } copy(devEUI[:], b) return devEUI, out, nil }
[ "func", "PopDownlinkFrame", "(", "p", "*", "redis", ".", "Pool", ",", "token", "uint32", ")", "(", "lorawan", ".", "EUI64", ",", "gw", ".", "DownlinkFrame", ",", "error", ")", "{", "var", "out", "gw", ".", "DownlinkFrame", "\n", "var", "devEUI", "lorawan", ".", "EUI64", "\n\n", "c", ":=", "p", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n\n", "b", ",", "err", ":=", "redis", ".", "Bytes", "(", "c", ".", "Do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "downlinkFramesKeyTempl", ",", "token", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "redis", ".", "ErrNil", "{", "return", "lorawan", ".", "EUI64", "{", "}", ",", "gw", ".", "DownlinkFrame", "{", "}", ",", "ErrDoesNotExist", "\n", "}", "\n", "return", "lorawan", ".", "EUI64", "{", "}", ",", "gw", ".", "DownlinkFrame", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "err", "=", "proto", ".", "Unmarshal", "(", "b", ",", "&", "out", ")", "\n", "if", "err", "!=", "nil", "{", "return", "lorawan", ".", "EUI64", "{", "}", ",", "gw", ".", "DownlinkFrame", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "b", ",", "err", "=", "redis", ".", "Bytes", "(", "c", ".", "Do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "downlinkFramesDevEUIKeyTempl", ",", "token", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "redis", ".", "ErrNil", "{", "return", "lorawan", ".", "EUI64", "{", "}", ",", "gw", ".", "DownlinkFrame", "{", "}", ",", "ErrDoesNotExist", "\n", "}", "\n", "return", "lorawan", ".", "EUI64", "{", "}", ",", "gw", ".", "DownlinkFrame", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "copy", "(", "devEUI", "[", ":", "]", ",", "b", ")", "\n\n", "return", "devEUI", ",", "out", ",", "nil", "\n", "}" ]
// PopDownlinkFrame returns the first downlink-frame for the given token.
[ "PopDownlinkFrame", "returns", "the", "first", "downlink", "-", "frame", "for", "the", "given", "token", "." ]
33ed6586ede637a540864142fcda0b7e3b90203d
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/downlink_frames.go#L69-L99
train