1// Copyright © 2021 Sören Tempel2//3// This program is free software: you can redistribute it and/or modify4// it under the terms of the GNU Affero General Public License as5// published by the Free Software Foundation, either version 3 of the6// License, or (at your option) any later version.7//8// This program is distributed in the hope that it will be useful, but9// WITHOUT ANY WARRANTY; without even the implied warranty of10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU11// Affero General Public License for more details.12//13// You should have received a copy of the GNU Affero General Public License14// along with this program. If not, see <https://www.gnu.org/licenses/>.1516const console = @import("console.zig");17const slipmux = @import("slipmux.zig");18const periph = @import("periph.zig");19const zoap = @import("zoap");20const codes = zoap.codes;2122const resources = &[_]zoap.Resource{23 .{ .path = "about", .handler = about },24 .{ .path = "on", .handler = ledOn },25 .{ .path = "off", .handler = ledOff },26};27var dispatcher = zoap.Dispatcher{28 .resources = resources,29};3031pub fn about(resp: *zoap.Response, req: *zoap.Request) codes.Code {32 if (!req.header.code.equal(codes.GET))33 return codes.BAD_METHOD;3435 console.print("[coap] Received /about request\n", .{});3637 const w = resp.payloadWriter();38 w.writeAll("zig-riscv-embedded licensed under AGPL3+") catch |err| {39 console.print("[coap] error in /about: {s}\n", .{@errorName(err)});40 return codes.INTERNAL_ERR;41 };4243 return codes.CONTENT;44}4546pub fn ledOn(resp: *zoap.Response, req: *zoap.Request) codes.Code {47 _ = resp; // Don't change response abort from code4849 if (!req.header.code.equal(codes.PUT))50 return codes.BAD_METHOD;5152 console.print("[coap] Turning LED on\n", .{});53 periph.gpio0.set(periph.led0, 0);5455 return codes.CHANGED;56}5758pub fn ledOff(resp: *zoap.Response, req: *zoap.Request) codes.Code {59 _ = resp; // Don't change response abort from code6061 if (!req.header.code.equal(codes.PUT))62 return codes.BAD_METHOD;6364 console.print("[coap] Turning LED off\n", .{});65 periph.gpio0.set(periph.led0, 1);6667 return codes.CHANGED;68}6970pub fn coapHandler(req: *zoap.Request) void {71 console.print("[coap] Incoming request\n", .{});72 var resp = dispatcher.dispatch(req) catch |err| {73 console.print("[coap] Dispatch failed: {s}\n", .{@errorName(err)});74 return;75 };7677 const ftype = slipmux.FrameType.coap;78 var frame = periph.slipmux.newFrame(ftype);7980 try frame.writer().writeAll(resp.marshal());81 frame.close();82}8384pub fn main() !void {85 try periph.slipmux.registerHandler(coapHandler);86 console.print("Waiting for incoming CoAP packets over UART0...\n", .{});87}