// Bytes returns the bytes func (m *Message) Bytes() []byte { if m.FPort == 0 { m.FPort = 1 } macPayload := &lorawan.MACPayload{} macPayload.FHDR = lorawan.FHDR{ DevAddr: lorawan.DevAddr(m.devAddr), FCnt: uint32(m.FCnt), } macPayload.FPort = pointer.Uint8(uint8(m.FPort)) macPayload.FRMPayload = []lorawan.Payload{&lorawan.DataPayload{Bytes: m.Payload}} phyPayload := &lorawan.PHYPayload{} phyPayload.MHDR = lorawan.MHDR{ MType: lorawan.UnconfirmedDataUp, Major: lorawan.LoRaWANR1, } if m.confirmed { phyPayload.MHDR.MType = lorawan.ConfirmedDataUp } phyPayload.MACPayload = macPayload phyPayload.EncryptFRMPayload(lorawan.AES128Key(m.appSKey)) phyPayload.SetMIC(lorawan.AES128Key(m.nwkSKey)) uplinkBytes, _ := phyPayload.MarshalBinary() return uplinkBytes }
func (h *handler) ConvertToLoRaWAN(ctx log.Interface, appDown *types.DownlinkMessage, ttnDown *pb_broker.DownlinkMessage) error { // Find Device dev, err := h.devices.Get(appDown.AppID, appDown.DevID) if err != nil { return err } // LoRaWAN: Unmarshal Downlink var phyPayload lorawan.PHYPayload err = phyPayload.UnmarshalBinary(ttnDown.Payload) if err != nil { return err } macPayload, ok := phyPayload.MACPayload.(*lorawan.MACPayload) if !ok { return errors.NewErrInvalidArgument("Downlink", "does not contain a MAC payload") } if ttnDown.DownlinkOption != nil && ttnDown.DownlinkOption.ProtocolConfig.GetLorawan() != nil { macPayload.FHDR.FCnt = ttnDown.DownlinkOption.ProtocolConfig.GetLorawan().FCnt } // Abort when downlink not needed if len(appDown.PayloadRaw) == 0 && !macPayload.FHDR.FCtrl.ACK && len(macPayload.FHDR.FOpts) == 0 { return ErrNotNeeded } // Set FPort if appDown.FPort != 0 { macPayload.FPort = &appDown.FPort } // Set Payload if len(appDown.PayloadRaw) > 0 { macPayload.FRMPayload = []lorawan.Payload{&lorawan.DataPayload{Bytes: appDown.PayloadRaw}} if macPayload.FPort == nil || *macPayload.FPort == 0 { macPayload.FPort = pointer.Uint8(1) } } else { macPayload.FRMPayload = []lorawan.Payload{} } // Encrypt err = phyPayload.EncryptFRMPayload(lorawan.AES128Key(dev.AppSKey)) if err != nil { return err } // Set MIC err = phyPayload.SetMIC(lorawan.AES128Key(dev.NwkSKey)) if err != nil { return err } // Marshal phyPayloadBytes, err := phyPayload.MarshalBinary() if err != nil { return err } ttnDown.Payload = phyPayloadBytes return nil }