無線が使えるとなると無性に無線でファームウェア更新がしたくなってくる。所謂OTAというやつだ。なので頑張って作ってみようとしたもののハマリどころ満載でメチャ時間がかかってしまった。(-_-;)
有線ならエラーなど発生することはあまりないが無線というのは同じ周波数帯を使う他の電子機器等の電波干渉に加え設置場所付近の障害物による電波の乱反射等により通信が不安定になったりするものだ。車庫などの狭い空間に自家用車があったりするとその駐車位置により通信できなくなったりすることもある。
例えばAデバイスからBデバイスに送信したときBデバイスが受信できなかった、或いは、Bデバイスは受信し結果を送信したのにAデバイスが受信できなかったという2つの事象が発生してしまうのが厄介だ。つまり受信できなかったのはどちらなのかががわからないため単純なリトライだけでは解決できないことがある。これを解決するには重複パケットの除去処理に加え送信の再送処理が必要となる。しかも通信相手が複数ある場合はその複数の相手毎に管理が必要だ。送信側は送信処理中に再送することは簡単ではあるが受信側は受信パケット処理後はメイン処理に戻ってしまうため処理結果の再送は少し面倒だ。しかも、複数の相手と通信してる場合はさらに厄介なことになる。ということを踏まえたうえで完璧とは言えないが最善と思われるロジックを考えてみた。
送信先デバイス毎に管理されるカウントアップカウンターを含むパケットを送信し受信したデバイスは送信元デバイス毎に管理するカウンターと違うなら新たなパケットとして処理を行い同じならリトライパケットと見なし直前の送信データがあれば再送する。送信デバイス側は送信後のレスポンスが受信できなければ前回と同じカウンター値で再送処理を行うというだけだ。これだけでどちら側が受信できなかったかにかかわらず確実な再送処理が可能となる。
【通信中のOTA-BRIDGE(MONOSTICK)】
※赤点滅は通信中。途中で通信が途切れても再送処理により復旧している。リトライは5回まで行うが1回目でほぼ復旧できるようだ。
OTAというとESP32などのように2分割したフラッシュ領域を交互に切り替えるのが一般的らしい。JN5169/JN5179であればフラッシュ領域が512Kbあるので問題ないがJN5164は160Kbしかないので単純に分割するとアプリ領域が不足してしまう。なので最初はJN5169でないと無理かなと思っていたがJN5164になんとか対応できる方法はないものかと思案してみたところある方法を思いついた。JN516xシリーズのフラッシュは32Kbのセクターに分割されていて各セクターは自由に論理アドレス空間にマッピングすることができ複数のアプリを書き込むことも可能となっている。ブートローダーはフラッシュの先頭から順に各セクターを検索し最初に発見した有効なアプリを起動するようになっているのでOTAブートローダーを最終セクターに書き込んでおいてOTAアップデートを開始するときにアプリを起動できないようにしてから再起動するとOTAブートローダーを起動することができる。この方法であればOTAブートローダーが占有するセクター以外をアプリ領域とすることができる。ということで可能な限り小さいOTAブートローダーを作ってみたところ1セクターにギリギリ収まってしまった。これなら1セクター(32Kb)だけアプリ領域が少なくなるだけなのでJN5164にも対応することが可能だ。但し、アプリは簡単に100Kbを超えてしまうためJN5164では余裕があまりない...
で、実際にアプリの書き換えを試してみると誤動作してしまう。なぜなのかわからなくて調査に時間がかかってしまったがSDKのFlash-APIの引数で指定するセクター番号やアドレスは物理アドレスではなくマッピング後の論理アドレスであることがわかった。このことはドキュメントのどこにも書かれていないし、ブートローダーのマッピングの仕方が少しヘンというかアプリ領域以外の空きセクターが順不同でマッピングされてしまう。最悪はマッピングされないセクターもあったりするようなので目的のセクターにアクセスするには自分で再マッピングしたほうが賢明だ。それらのことを知らないとSDKのFlash-APIは使いものにならないだろう。
OTAブートローダーの機能はWPanクラスに組み込んである。なのでアプリは自動的にOTA対応になる。アプリで何か特別なことを行う必要もなく単にWPan::begin()を呼び出しWPanクラスを開始するだけでOKだ。またOTAブートローダーアプリ(最小サイズのOTAアプリ)もOTAで書き込めるようにしてみた。最初の書き込みにはプログラマーが必要であるが一度OTA対応アブリを書き込めばいつでもOTAアップデート可能となる。但し、アプリのアップデートに先立ち一度だけOTAブートローダーアプリの書き込みが必要となる。前もって書き込んでおくことも可能だが前投稿で紹介したプログラマーを使う必要がある。他社のプログラマーは一つのアプリしか書けないので使用できない。
【接続図】
PC(JN516X-OTA.exe)<--USB-->MONOSTICK(OTA-BRIDGE.bin)<--Wireless-->JN516X(OTA-BOOT.bin)
【使い方】
1.setup()にてWPan::begin(0)を実行するアプリ(userapp.bin)を作成し書き込んだデバイスを起動しておく。
※動作確認用にLチカ・アプリなどが最適。
2.OTA-BRIDGE.binを書き込んだデバイスをUSB接続する。
※TWELITE-R(2)/MONISTICK(推奨)が必要。
3.USB接続先の番号を調べる
例:JN516X-OTA.exe -s
4.USB接続先の番号、ターゲットデバイスの無線アドレスとOTA-BOOT.binファイルを指定して実行する。(一度だけでOK)
例:JN516X-OTA.exe -p 2 -a 0 -w JN5164-MWSDK-OTA-BOOT.bin
5.USB接続先の番号、ターゲットデバイスの無線アドレスと書き込むuserapp.binファイルを指定して実行する。
例:JN516X-OTA.exe -p 2 -a 0 -w userapp.bin
6.途中でエラー時はアドレスに65534を指定し再実行する。(稀にある)
例:JN516X-OTA.exe -p 2 -a 65534 -w userapp.bin
【修正履歴】
2022-06-01
JN5164で作成したプログラムが書き込みできなくて調べてみたらチップがJN5168だった。JN5161/JN5164/JN5168は同一パイナリーで動作するのでJN5161/JN5164/JN5168については同一チップと見なすように変更した。
【ダウンロード(eclipseプロジェクト)】
JN516X-OTA-eclipse
JN5164-MWSDK-OTA-BOOT-eclipse
JN5164-MWSDK-OTA-BRIDGE-eclipse
JN5169-MWSDK-OTA-BOOT-eclipse
JN5169-MWSDK-OTA-BRIDGE-eclipse
【OTA Update Utility】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
/* main.cpp - OTA Update Utility for NXP JN516x Series Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include "jn516x_ota.h" class Device : public JN516x_OTA { public: Device(void) {} virtual ~Device(void) {} protected: void programStart(const char *chipname, const char *filename, bool program) override { if (program) printf("Write Device [%s] <- \"%s\"\n", chipname, filename); else printf("Read Device [%s] -> \"%s\"\n", chipname, filename); } void programProgress(size_t size, size_t processed) override { printf("Progress: %6llu/%6llu\r", processed, size); } void programEnd(STATUS status) override { if (status == STATUS_OK) printf("\nSuccess.\n"); else if (status == STATUS_INVALID_DEVICE) printf("\nError: Not Supported Device\n"); else if (status == STATUS_INVALID_FILE) printf("\nError: Other device binaries (.bin)\n"); else printf("\nError: 0x%02X\n", status); } }; static Device device; void chipInfo(void) { Device::VERSION version; Device::STATUS status = device.chipVersion(version); if (status == Device::STATUS_OK) { printf("Chip Name: %s", device.chipName(version)); printf(", Flash: %u Kb, Ram: %u Kb, Type: %u\n", device.chipFlashSize(version) / 1024, device.chipRamSize(version) / 1024, device.chipType(version)); } else printf("Error: 0x%02X\n", status); } void portScan(void) { int count = device.getDeviceCount(); printf("Device Count: %d\n", count); for (int i = 0; i < count; ++i) { char buf[128]; printf("Device-%d: ", i); if (device.begin(i)) { printf("Port: Com%u", device.getComPortNumber()); device.end(); device.getDeviceSerial(i, buf); printf(", Serial: %s", buf); device.getDeviceDescription(i, buf); printf(", Description: %s", buf); } else printf("-- Open failure --"); printf("\n"); } } void usage(bool help) { printf("OTA Update Utility for NXP JN516X, Version 1.0\n"); printf("Copyright(c) 2022 Sasapea's Lab. All right reserved.\n"); printf("\n"); if (help) { printf("Usage: JN516X-OTA [options]\n"); printf("\n"); printf(" options:\n"); printf(" -s ... FTD2XX Port Scan\n"); printf(" -p portname ... FTD2XX Serial Number for Open\n"); printf(" -w filename ... write device (.bin)\n"); printf(" -a address ... device address (*0 - n)\n"); printf(" -d ... device information\n"); printf(" -h ... this help\n"); printf("\n"); } } int main(int argc, char **argv) { bool help = false; bool scan = false; bool info = false; const char *portname = ""; const char *firmware = ""; Device::SPEED speed = Device::SPEED_1M; uint16_t address = 0; for (int i = 1; i < argc; ) { char *p = argv[i++]; if (*p == '-') { switch (*++p) { case 'h': help = true; break; case 's': scan = true; break; case 'p': if (i < argc) portname = argv[i++]; break; case 'w': if (i < argc) firmware = argv[i++]; break; case 'a': if (i < argc) address = atoi(argv[i++]); break; case 'd': info = true; break; default: help = true; break; } } else help = true; } if (help) usage(true); else if (device.status() != FT_OK) { usage(false); printf("FTD2XX Library Not Found."); } else if (scan) { usage(false); portScan(); } else if (device.begin(portname, speed, address, argv[0])) { usage(false); if (info) chipInfo(); if (*firmware) device.update(firmware); device.end(); } else { usage(false); printf("Port Open Failed: \"%s\"\n", portname); } return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 |
/* jn516x_ota.h - OTA Library for NXP JN516x Series Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include "ftd2.h" #include "crc32.h" #include "sleep.h" #include "jn516x.h" #define DEBUG_TX_PACKET_DUMP 0 #define DEBUG_RX_PACKET_DUMP 0 #define OTA_RETRY_COUNT 5 #define OTA_BOOT_FARMWARE "-OTA-BOOT.bin" #define ACK 0x06 #define NAK 0x15 class JN516x_OTA : public JN516x, public FTD2 { public: typedef enum { STATUS_OK = OTA_STATUS_OK, STATUS_ARG_ERROR = OTA_STATUS_ARG_ERROR, STATUS_BLD_ERROR = OTA_STATUS_BLD_ERROR, STATUS_CRC_ERROR = OTA_STATUS_CRC_ERROR, STATUS_SDK_ERROR = OTA_STATUS_SDK_ERROR, STATUS_INVALID_DEVICE = 0xF0, STATUS_INVALID_FILE = 0xF1, STATUS_OPEN_ERROR = 0xF2, STATUS_READ_ERROR = 0xF3, STATUS_TX_ERROR = 0xF4, STATUS_RX_ERROR = 0xF5, } STATUS; JN516x_OTA(void) : _address(0) , _otaboot(false) { } virtual ~JN516x_OTA(void) { } bool begin(int index) { return FTD2::begin(index); } bool begin(const char *portname, SPEED speed, uint16_t addr, const char *argv0) { _address = addr; savePath(_path, argv0); return FTD2::begin(portname, speed, MODE_8N1, FLOW_RTS_CTS); } STATUS update(const char *filename) { STATUS status; VERSION chipver; status = chipVersion(chipver); programStart(chipName(chipver), filename, true); if (status == STATUS_OK) { if (!chipver) status = STATUS_INVALID_DEVICE; else { FILE *fp; status = STATUS_OPEN_ERROR; if ((fp = fopen(filename, "rb"))) { VERSION filever; if (!fileVersion(filever, fp)) status = STATUS_READ_ERROR; else if (chipver != filever) status = STATUS_INVALID_FILE; else { size_t fpos = (chipver == VERSION_JN5179 ? 0 : ftell(fp)); fseek(fp, 0, SEEK_END); size_t size = ftell(fp) - fpos; fseek(fp, fpos, SEEK_SET); if (size >= FLASH_SECTOR_OFFSET(chipFlashSectors(chipver) - 1)) status = STATUS_INVALID_FILE; else if (!strstr(filename, OTA_BOOT_FARMWARE)) status = ota(fp, size, _address); // Update App else if (size <= FLASH_SECTOR_OFFSET(1)) status = ota(fp, size, _address, true); // Update OTA-BOOT else status = STATUS_INVALID_FILE; } fclose(fp); } } } programEnd(status); return status; } STATUS chipVersion(VERSION& version) { STATUS status = protocol(_address, OTA_UPDATE_CHIPVER); version = (VERSION)(status == STATUS_OK ? read32(_packet + 3) : 0); _otaboot = _packet[7]; return status; } protected: virtual void programStart(const char *chipname, const char *filename, bool program) {} virtual void programProgress(size_t size, size_t processed) {} virtual void programEnd(STATUS status) {} private: bool fileVersion(VERSION& version, FILE *fp) { uint8_t data[4]; fseek(fp, 0, SEEK_SET); if (fread(data, 1, sizeof(data), fp) != sizeof(data)) return false; version = (VERSION)read32(data); return true; } void savePath(char *save, const char *path) { char c, *dir = save; while (*path) { c = *save++ = *path++; if ((c == '/') || (c == '\\')) dir = save; } *dir = 0; } void write32(uint8_t *buf, uint32_t data) { buf[3] = (uint8_t)(data >> 0); buf[2] = (uint8_t)(data >> 8); buf[1] = (uint8_t)(data >> 16); buf[0] = (uint8_t)(data >> 24); } uint32_t read32(const uint8_t *buf) { return ((uint32_t)buf[0] << 24) | ((uint32_t)buf[1] << 16) | ((uint16_t)buf[2] << 8) | ((uint8_t )buf[3] << 0); } void dump(const uint8_t *buf, uint8_t len) { int i = 0; while (i < len) { printf("%02X ", *buf++); if ((++i % 16) == 0) printf("\n"); } if ((i % 16) != 0) printf("\n"); } uint8_t csum(void *buf, size_t len) { uint8_t *p = (uint8_t *)buf; uint8_t c = 0; while (len--) c ^= *p++; return c; } STATUS protocol(uint16_t addr, OTA_UPDATE cmd, const uint8_t *buf = 0, uint8_t len = 0) { STATUS status; size_t n, cnt; // packet[0]: len (n + 4) // packet[1]: addr-hi // packet[2]: addr-lo // packet[3]: command // packet[4]: data (n bytes) // packet[4 + n]: csum for (int i = 0; i < OTA_RETRY_COUNT; ++i) { uint8_t ack = NAK; for (int j = 0; j < 3; ++j) { _packet[1] = (uint8_t)(addr >> 8); _packet[2] = (uint8_t)(addr >> 0); _packet[3] = cmd; memcpy(_packet + 4, buf, len); _packet[0] = cnt = 4 + len; _packet[cnt] = csum(_packet, cnt); ++cnt; #if DEBUG_TX_PACKET_DUMP dump(_packet, cnt); #endif if (write(_packet, cnt) == cnt) { if (read(&ack, sizeof(ack)) == sizeof(ack)) { if (ack == ACK) break; } } Sleep::sleep(100); } if (ack == NAK) return STATUS_TX_ERROR; for (cnt = _packet[0] = 0; cnt <= _packet[0]; cnt += n) { if ((n = read(_packet + cnt, _packet[0] - cnt + 1)) == 0) break; } #if DEBUG_RX_PACKET_DUMP if (_packet[1] == OTA_UPDATE_CHIPVER) dump(_packet, cnt); #endif if (cnt < 4) status = STATUS_RX_ERROR; else if (csum(_packet, cnt)) status = STATUS_CRC_ERROR; else return (STATUS)_packet[2]; cmd = OTA_UPDATE_RETRY; len = 0; Sleep::sleep(100); } return status; } STATUS ota(FILE *fp, size_t size, uint16_t addr, bool bldupd = false) { STATUS status; uint8_t len, buf[96]; buf[0] = bldupd ? 0xBF : 0x00; if (!_otaboot && !bldupd) status = STATUS_BLD_ERROR; else if ((status = protocol(addr, OTA_UPDATE_BLDMODE, buf, sizeof(buf[0]))) == STATUS_OK) { if (!bldupd) { Sleep::sleep(500); addr = ADDR_OTA_BOOT; } if ((status = protocol(addr, OTA_UPDATE_START)) == STATUS_OK) { size_t progress = 0; size_t prog = 0; CRC32::init(); size = (size + 15) & ~0x0F; // 16-byte boundary while (1) { memset(buf, 0xFF, sizeof(buf)); if ((len = (size_t)fread(buf, 1, sizeof(buf), fp)) == 0) break; len = (len + 15) & ~0x0F; // 16-byte boundary if ((status = protocol(addr, OTA_UPDATE_PROGRAM, buf, len)) != STATUS_OK) break; CRC32::update(buf, len); progress += len; if (prog != (progress >> 10)) { prog = (progress >> 10); programProgress(size, progress); } } programProgress(size, progress); } write32(buf, CRC32::result()); status = protocol(addr, OTA_UPDATE_END, buf, 4); } return status; } uint16_t _address; bool _otaboot; uint8_t _packet[256]; char _path[PATH_MAX]; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
/* sleep.h - Sleep Library Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #ifdef __linux__ #include <time.h> #else #include <windows.h> #endif class Sleep { public: static void sleep(unsigned long ms) { #ifdef __linux__ struct timespec req; req.tv_sec = (ms / 1000); req.tv_nsec = (ms % 1000) * 1000000; nanosleep(&req, NULL); #else ::Sleep(ms); #endif } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
/* crc32.cpp - CRC32 Library Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <stdint.h> class CRC32 { public: typedef enum { POLY_IEEE802_3 = 0xEDB88320, // CRC-32-IEEE 802.3 } POLY; static void init(uint32_t initval = (uint32_t)-1, POLY poly = POLY_IEEE802_3) { _result = initval; for (uint32_t i = 0; i < 256; i++) { uint32_t c = i; for (int j = 0; j < 8; j++) c = c & 1 ? poly ^ (c >> 1) : c >> 1; _lookup[i] = c; } } static void update(const uint8_t *buf, uint32_t len) { for (uint32_t i = 0; i < len; i++) _result = _lookup[(_result ^ *buf++) & 0xFF] ^ (_result >> 8); } static uint32_t result(uint32_t xorout = (uint32_t)-1) { return _result ^ xorout; } private: static uint32_t _result; static uint32_t _lookup[256]; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/* crc32.cpp - CRC32 Library Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "crc32.h" uint32_t CRC32::_result; uint32_t CRC32::_lookup[256]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
/* jn516x.h - JN516x Chip Library for NXP JN516x Series Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <stdint.h> #define FLASH_START_ADDRESS 0x80000U #define FLASH_SECTOR_OFFSET(sec) (0x8000U * (sec)) class JN516x { public: static const uint8_t MAGICNUMBER[12]; static const uint8_t MAGICNUMBER_JN5179[12]; typedef struct __attribute__((packed)) { uint8_t magicNumber[12]; uint8_t configuration; uint8_t status; uint16_t applicationID; } tsBIR; typedef struct __attribute__((packed)) { tsBIR sBIR; // 16-byte Boot Image Record uint8_t encryption[14]; // Encryption Initialisation Vector (ignored if unencrypted) uint16_t configuration; // 16-bit Software Configuration Options uint32_t imageSize; // 32-bit Length of Binary Image in bytes uint32_t dataStart; // 32-bit .data section Flash start address uint16_t dataAddress; // 16-bit .data section load address in RAM (word aligned) uint16_t dataLength; // 16-bit .data section length in 32-bit words uint16_t bssStart; // 16 bit .bss section start address in RAM (word aligned) uint16_t bssLength; // 16-bit .bss section length in 32-bit words uint32_t warmStart; // 32-bit wake-up entry point (word aligned) – warm start uint32_t coldStart; // 32-bit reset entry point (word aligned) – cold start } tsFlashHeader; typedef struct __attribute__((packed)) { uint32_t version; // version tsBIR sBIR; // 16-byte Boot Image Record uint8_t encryption[14]; // Encryption Initialisation Vector (ignored if unencrypted) uint16_t configuration; // 16-bit Software Configuration Options uint32_t imageSize; // 32-bit Length of Binary Image in bytes uint32_t dataStart; // 32-bit .data section Flash start address uint16_t dataAddress; // 16-bit .data section load address in RAM (word aligned) uint16_t dataLength; // 16-bit .data section length in 32-bit words uint16_t bssStart; // 16 bit .bss section start address in RAM (word aligned) uint16_t bssLength; // 16-bit .bss section length in 32-bit words uint32_t warmStart; // 32-bit wake-up entry point (word aligned) – warm start uint32_t coldStart; // 32-bit reset entry point (word aligned) – cold start } tsFlashHeader_JN5179; typedef enum { CHIPID_JN5179 = 1U, // Survey required. CHIPID_JN5169 = 0x0100B686U, CHIPID_JN5168 = 0x10008686U, CHIPID_JN5164 = 0x10408686U, CHIPID_JN5161 = 0U, // Survey required. CHIPID_JN5148 = 0x10404686U, CHIPID_JN5142 = 0x00005686U, CHIPID_JN5139 = 0x10002000U, } CHIPID; typedef enum { VERSION_JN5179 = 0x0F03000AU, VERSION_JN5169 = 0x0F03000BU, VERSION_JN5168 = 0x07030008U, VERSION_JN5164 = 0x04030008U, VERSION_JN5161 = 0x01000008U, } VERSION; typedef enum { FLASHID_ST_M25P05_A = 0x0505U, FLASHID_ST_M25P10_A = 0x1010U, FLASHID_ST_M25P20_A = 0x1101U, FLASHID_ST_M25P40 = 0x1212U, FLASHID_SST_25VF010A = 0xBF49U, FLASHID_ATMEL_25F512 = 0x1F60U, FLASHID_INTERNAL_FLASH = 0xCCEEU, // JN516x/7x only } FLASHID; typedef enum { FLASH_ST_M25P05_A = 4U, FLASH_ST_M25P10_A = 0U, FLASH_ST_M25P20_A = 5U, FLASH_ST_M25P40 = 3U, FLASH_SST_25VF010A = 1U, FLASH_ATMEL_25F512 = 2U, FLASH_INTERNAL_FLASH = 8U, // JN516x/7x only } FLASH; typedef enum { ADDR_BROADCAST = 0xFFFFU, ADDR_OTA_BOOT = ADDR_BROADCAST - 1, ADDR_OTA_BRIDGE = ADDR_BROADCAST - 2, ADDR_OTA_BRIDGE2 = ADDR_BROADCAST - 3, } ADDR; typedef enum { OTA_UPDATE_CHIPVER = 0xC0U, OTA_UPDATE_BLDMODE = 0xC1U, OTA_UPDATE_START = 0xC2U, OTA_UPDATE_PROGRAM = 0xC3U, OTA_UPDATE_END = 0xC4U, OTA_UPDATE_RETRY = 0xC5U, /* only Bridge */ } OTA_UPDATE; typedef enum { OTA_STATUS_OK = 0x00U, OTA_STATUS_ARG_ERROR = 0xFAU, OTA_STATUS_BLD_ERROR = 0xFBU, OTA_STATUS_CRC_ERROR = 0xFCU, OTA_STATUS_SDK_ERROR = 0xFDU, } OTA_STATUS; static VERSION chipVersion(CHIPID id) { switch (id) { case CHIPID_JN5179: return VERSION_JN5179; case CHIPID_JN5169: return VERSION_JN5169; case CHIPID_JN5168: return VERSION_JN5168; case CHIPID_JN5164: return VERSION_JN5164; case CHIPID_JN5161: return VERSION_JN5161; default: break; } return (VERSION)0; } static const char *chipName(VERSION version) { switch (version) { case VERSION_JN5179: return "JN5179"; case VERSION_JN5169: return "JN5169"; case VERSION_JN5168: return "JN5168"; case VERSION_JN5164: return "JN5164"; case VERSION_JN5161: return "JN5161"; default: break; } return "(unknown)"; } static uint32_t chipFlashSectors(VERSION version) { return (uint8_t)(version >> 24) + 1; } static uint32_t chipFlashSize(VERSION version) { return 32768U * chipFlashSectors(version); } static uint32_t chipRamSize(VERSION version) { return 8192U * ((uint8_t)(version >> 16) + 1); } static uint16_t chipType(VERSION version) { return (uint16_t)version; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/* jn516x.cpp - JN516x Chip Library for NXP JN516x Series Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "jn516x.h" const uint8_t JN516x::MAGICNUMBER[] = { 0x12, 0x34, 0x56, 0x78, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; const uint8_t JN516x::MAGICNUMBER_JN5179[] = { 0x12, 0x34, 0x56, 0x78, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99 }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
/* ftd2.h - Serial Library for FTDI USB Chip FT2XX Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include "ftd2xx.h" #include "sleep.h" #ifndef LOW #define LOW 0 #endif #ifndef HIGH #define HIGH 1 #endif extern FT_STATUS FT_GetLastError(void); class FTD2 { public: // // FT_OpenEx Flags // typedef enum { OPENBY_SERIAL_NUMBER = FT_OPEN_BY_SERIAL_NUMBER, OPENBY_DESCRIPTION = FT_OPEN_BY_DESCRIPTION, OPENBY_LOCATION = FT_OPEN_BY_LOCATION, } OPENBY; // // Baud Rates // typedef enum { SPEED_300 = FT_BAUD_300, SPEED_600 = FT_BAUD_600, SPEED_1200 = FT_BAUD_1200, SPEED_2400 = FT_BAUD_2400, SPEED_4800 = FT_BAUD_4800, SPEED_9600 = FT_BAUD_9600, SPEED_14400 = FT_BAUD_14400, SPEED_19200 = FT_BAUD_19200, SPEED_38400 = FT_BAUD_38400, SPEED_57600 = FT_BAUD_57600, SPEED_115200 = FT_BAUD_115200, SPEED_230400 = FT_BAUD_230400, SPEED_460800 = FT_BAUD_460800, SPEED_500K = 500000, SPEED_921600 = FT_BAUD_921600, SPEED_1M = 1000000, SPEED_2M = 2000000, SPEED_3M = 3000000, } SPEED; // // mode // typedef enum { MODE_7N1 = 0, MODE_8N1 = 1, MODE_7N2 = 2, MODE_8N2 = 3, MODE_7E1 = 4, MODE_8E1 = 5, MODE_7E2 = 6, MODE_8E2 = 7, MODE_7O1 = 8, MODE_8O1 = 9, MODE_7O2 = 10, MODE_8O2 = 11, } MODE; // // Flow Control // typedef enum { FLOW_NONE = FT_FLOW_NONE, FLOW_RTS_CTS = FT_FLOW_RTS_CTS, FLOW_DTR_DSR = FT_FLOW_DTR_DSR, FLOW_XON_XOFF = FT_FLOW_XON_XOFF, } FLOW; // // Bit Modes // typedef enum { BITMODE_RESET = FT_BITMODE_RESET, BITMODE_ASYNC_BITBANG = FT_BITMODE_ASYNC_BITBANG, BITMODE_MPSSE = FT_BITMODE_MPSSE, BITMODE_SYNC_BITBANG = FT_BITMODE_SYNC_BITBANG, BITMODE_MCU_HOST = FT_BITMODE_MCU_HOST, BITMODE_FAST_SERIAL = FT_BITMODE_FAST_SERIAL, BITMODE_CBUS_BITBANG = FT_BITMODE_CBUS_BITBANG, BITMODE_SYNC_FIFO = FT_BITMODE_SYNC_FIFO, } BITMODE; typedef enum { GPIO_INPUT = 0, GPIO_OUTPUT = 1, } GPIO; typedef enum { CBUS_0 = 0, CBUS_1 = 1, CBUS_2 = 2, CBUS_3 = 3, } CBUS; FTD2(BITMODE mode = BITMODE_CBUS_BITBANG) : _handle(0) , _mode(mode) , _cbus(0) { FT_Initialise(); } virtual ~FTD2(void) { end(); FT_Finalise(); } FT_STATUS status(void) { return FT_GetLastError(); } size_t getDeviceCount(void) { DWORD count = 0; FT_ListDevices(&count, NULL, FT_LIST_NUMBER_ONLY); return count; } bool getDeviceSerial(size_t index, char *buf) { strcpy(buf, "(null)"); return FT_SUCCESS(FT_ListDevices((void *)index, buf, FT_LIST_BY_INDEX | FT_OPEN_BY_SERIAL_NUMBER)); } bool getDeviceDescription(size_t index, char *buf) { strcpy(buf, "(null)"); return FT_SUCCESS(FT_ListDevices((void *)index, buf, FT_LIST_BY_INDEX | FT_OPEN_BY_DESCRIPTION)); } bool getDeviceLocation(size_t index, char *buf) { strcpy(buf, "(null)"); return FT_SUCCESS(FT_ListDevices((void *)index, buf, FT_LIST_BY_INDEX | FT_OPEN_BY_LOCATION)); } bool begin(int index, SPEED speed = SPEED_115200, MODE mode = MODE_8N1, FLOW flow = FLOW_NONE) { if (!FT_SUCCESS(FT_Open(index, &_handle))) return false; init(speed, mode, flow); return true; } bool begin(const char *name, SPEED speed = SPEED_115200, MODE mode = MODE_8N1, FLOW flow = FLOW_NONE) { char *eos; int index = strtoul(name, &eos, 10); if (*eos) { if (!FT_SUCCESS(FT_OpenEx((void *)name, OPENBY_SERIAL_NUMBER, &_handle))) return false; } else { if (!FT_SUCCESS(FT_Open(index, &_handle))) return false; } init(speed, mode, flow); return true; } bool end(void) { if (_handle) { FT_HANDLE h = _handle; _handle = nullptr; return FT_SUCCESS(FT_Close(h)); } return true; } int getComPortNumber(void) { LONG com = -1; FT_GetComPortNumber(_handle, &com); return com; } bool baudrate(SPEED speed) { switch (speed) { case SPEED_500K: return FT_SUCCESS(FT_SetDivisor(_handle, 6)); case SPEED_1M: return FT_SUCCESS(FT_SetDivisor(_handle, 3)); case SPEED_2M: return FT_SUCCESS(FT_SetDivisor(_handle, 1)); case SPEED_3M: return FT_SUCCESS(FT_SetDivisor(_handle, 0)); default: break; } return FT_SUCCESS(FT_SetBaudRate(_handle, speed)); } bool frame(MODE mode = MODE_8N1) { return FT_SUCCESS(FT_SetDataCharacteristics(_handle, mode & 1 ? DATA_8 : DATA_7, mode & 2 ? STOP_2 : STOP_1, mode & 4 ? PAR_EVEN : (mode & 8 ? PAR_NONE : PAR_NONE) )); } bool flowCtrl(FLOW mode, uint8_t xon = 0x11, uint8_t xoff = 0x13) { return FT_SUCCESS(FT_SetFlowControl(_handle, mode, xon, xoff)); } bool dtr(bool on) { return FT_SUCCESS(on ? FT_SetDtr(_handle) : FT_ClrDtr(_handle)); } bool rts(bool on) { return FT_SUCCESS(on ? FT_SetRts(_handle) : FT_ClrRts(_handle)); } bool timeout(uint32_t readTimeout, uint32_t writeTimeout) { return FT_SUCCESS(FT_SetTimeouts(_handle, readTimeout, writeTimeout)); } bool purge(void) { return FT_SUCCESS(FT_Purge(_handle, FT_PURGE_RX | FT_PURGE_TX)); } size_t read(void *buf, size_t len) { DWORD bytesReceived = 0; FT_Read(_handle, buf, len, &bytesReceived); return bytesReceived; } size_t write(const void *buf, size_t len) { DWORD bytesWritten = 0; FT_Write(_handle, (void *)buf, len, &bytesWritten); return bytesWritten; } void pinMode(CBUS pin, GPIO mode) { pin = (CBUS)((pin & 3) + 4); if (mode == GPIO_OUTPUT) _cbus |= (1 << pin); else _cbus &= ~(1 << pin); FT_SetBitMode(_handle, _cbus, _mode); } void digitalWrite(CBUS pin, uint8_t value) { pin = (CBUS)(pin & 3); if (value) _cbus |= (1 << pin); else _cbus &= ~(1 << pin); FT_SetBitMode(_handle, _cbus, _mode); } uint8_t digitalRead(CBUS pin) { pin = (CBUS)(pin & 3); uint8_t mask = _cbus >> 4; uint8_t data = 0; FT_GetBitMode(_handle, &data); return (((data & ~mask) | (_cbus & mask)) >> pin) & 1; } protected: void init(SPEED speed, MODE mode, FLOW flow) { baudrate(speed); frame(mode); flowCtrl(flow); rts(true); dtr(true); timeout(1000, 1000); purge(); FT_SetBitMode(_handle, _cbus, BITMODE_RESET); } private: // // Word Lengths // typedef enum { DATA_8 = FT_BITS_8, DATA_7 = FT_BITS_7, } DATA; // // Stop Bits // typedef enum { STOP_1 = FT_STOP_BITS_1, STOP_2 = FT_STOP_BITS_2, } STOP; // // Parity // typedef enum { PAR_NONE = FT_PARITY_NONE, PAR_ODD = FT_PARITY_ODD, PAR_EVEN = FT_PARITY_EVEN, PAR_MARK = FT_PARITY_MARK, PAR_SPACE = FT_PARITY_SPACE, } PAR; FT_HANDLE _handle; uint8_t _mode; uint8_t _cbus; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
/* ftd2.cpp - Serial Library for FTDI USB Chip FT2XX Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ftd2.h" typedef FT_STATUS (WINAPI *LPFN_FT_ListDevices)(PVOID pvArg1, PVOID pvArg2, DWORD dwFlags); typedef FT_STATUS (WINAPI *LPFN_FT_Open)(int iDevice, FT_HANDLE *ftHandle); typedef FT_STATUS (WINAPI *LPFN_FT_OpenEx)(PVOID pArg1, DWORD Flags, FT_HANDLE *pHandle); typedef FT_STATUS (WINAPI *LPFN_FT_Close)(FT_HANDLE ftHandle); typedef FT_STATUS (WINAPI *LPFN_FT_SetTimeouts)(FT_HANDLE ftHandle, DWORD dwReadTimeout, DWORD dwWriteTimeout); typedef FT_STATUS (WINAPI *LPFN_FT_Read)(FT_HANDLE ftHandle, LPVOID lpBuffer, DWORD dwBytesToRead, LPDWORD lpBytesReturned); typedef FT_STATUS (WINAPI *LPFN_FT_Write)(FT_HANDLE ftHandle, LPVOID lpBuffer, DWORD dwBytesToWrite, LPDWORD lpBytesWritten); typedef FT_STATUS (WINAPI *LPFN_FT_SetBaudRate)(FT_HANDLE ftHandle, ULONG BaudRate); typedef FT_STATUS (WINAPI *LPFN_FT_SetDivisor)(FT_HANDLE ftHandle, USHORT usDivisor); typedef FT_STATUS (WINAPI *LPFN_FT_SetDataCharacteristics)(FT_HANDLE ftHandle, UCHAR WordLength, UCHAR StopBits, UCHAR Parity); typedef FT_STATUS (WINAPI *LPFN_FT_SetFlowControl)(FT_HANDLE ftHandle, USHORT FlowControl, UCHAR XonChar, UCHAR XoffChar); typedef FT_STATUS (WINAPI *LPFN_FT_SetDtr)(FT_HANDLE ftHandle); typedef FT_STATUS (WINAPI *LPFN_FT_ClrDtr)(FT_HANDLE ftHandle); typedef FT_STATUS (WINAPI *LPFN_FT_SetRts)(FT_HANDLE ftHandle); typedef FT_STATUS (WINAPI *LPFN_FT_ClrRts)(FT_HANDLE ftHandle); typedef FT_STATUS (WINAPI *LPFN_FT_SetBitMode)(FT_HANDLE ftHandle, UCHAR ucMask, UCHAR ucEnable); typedef FT_STATUS (WINAPI *LPFN_FT_GetBitMode)(FT_HANDLE ftHandle, PUCHAR pucMode); typedef FT_STATUS (WINAPI *LPFN_FT_GetComPortNumber)(FT_HANDLE ftHandle, LPLONG lplComPortNumber); typedef FT_STATUS (WINAPI *LPFN_FT_Purge)(FT_HANDLE ftHandle, ULONG Mask); static HMODULE hFTD2XX; static LPFN_FT_ListDevices lpfn_FT_ListDevices; static LPFN_FT_Open lpfn_FT_Open; static LPFN_FT_OpenEx lpfn_FT_OpenEx; static LPFN_FT_Close lpfn_FT_Close; static LPFN_FT_SetTimeouts lpfn_FT_SetTimeouts; static LPFN_FT_Read lpfn_FT_Read; static LPFN_FT_Write lpfn_FT_Write; static LPFN_FT_SetBaudRate lpfn_FT_SetBaudRate; static LPFN_FT_SetDivisor lpfn_FT_SetDivisor; static LPFN_FT_SetDataCharacteristics lpfn_FT_SetDataCharacteristics; static LPFN_FT_SetFlowControl lpfn_FT_SetFlowControl; static LPFN_FT_SetDtr lpfn_FT_SetDtr; static LPFN_FT_ClrDtr lpfn_FT_ClrDtr; static LPFN_FT_SetRts lpfn_FT_SetRts; static LPFN_FT_ClrRts lpfn_FT_ClrRts; static LPFN_FT_SetBitMode lpfn_FT_SetBitMode; static LPFN_FT_GetBitMode lpfn_FT_GetBitMode; static LPFN_FT_GetComPortNumber lpfn_FT_GetComPortNumber; static LPFN_FT_Purge lpfn_FT_Purge; static FT_STATUS status = FT_OK; FT_STATUS FT_GetLastError(void) { return status; } FT_STATUS WINAPI FT_Initialise(void) { if (!hFTD2XX) { if (!(hFTD2XX = LoadLibrary("ftd2xx.dll"))) return status = FT_NOT_SUPPORTED; lpfn_FT_ListDevices = (LPFN_FT_ListDevices) GetProcAddress(hFTD2XX, "FT_ListDevices"); lpfn_FT_Open = (LPFN_FT_Open) GetProcAddress(hFTD2XX, "FT_Open"); lpfn_FT_OpenEx = (LPFN_FT_OpenEx) GetProcAddress(hFTD2XX, "FT_OpenEx"); lpfn_FT_Close = (LPFN_FT_Close) GetProcAddress(hFTD2XX, "FT_Close"); lpfn_FT_SetTimeouts = (LPFN_FT_SetTimeouts) GetProcAddress(hFTD2XX, "FT_SetTimeouts"); lpfn_FT_Read = (LPFN_FT_Read) GetProcAddress(hFTD2XX, "FT_Read"); lpfn_FT_Write = (LPFN_FT_Write) GetProcAddress(hFTD2XX, "FT_Write"); lpfn_FT_SetBaudRate = (LPFN_FT_SetBaudRate) GetProcAddress(hFTD2XX, "FT_SetBaudRate"); lpfn_FT_SetDivisor = (LPFN_FT_SetDivisor) GetProcAddress(hFTD2XX, "FT_SetDivisor"); lpfn_FT_SetDataCharacteristics = (LPFN_FT_SetDataCharacteristics)GetProcAddress(hFTD2XX, "FT_SetDataCharacteristics"); lpfn_FT_SetFlowControl = (LPFN_FT_SetFlowControl) GetProcAddress(hFTD2XX, "FT_SetFlowControl"); lpfn_FT_SetDtr = (LPFN_FT_SetDtr) GetProcAddress(hFTD2XX, "FT_SetDtr"); lpfn_FT_ClrDtr = (LPFN_FT_ClrDtr) GetProcAddress(hFTD2XX, "FT_ClrDtr"); lpfn_FT_SetRts = (LPFN_FT_SetRts) GetProcAddress(hFTD2XX, "FT_SetRts"); lpfn_FT_ClrRts = (LPFN_FT_ClrRts) GetProcAddress(hFTD2XX, "FT_ClrRts"); lpfn_FT_SetBitMode = (LPFN_FT_SetBitMode) GetProcAddress(hFTD2XX, "FT_SetBitMode"); lpfn_FT_GetBitMode = (LPFN_FT_GetBitMode) GetProcAddress(hFTD2XX, "FT_GetBitMode"); lpfn_FT_GetComPortNumber = (LPFN_FT_GetComPortNumber) GetProcAddress(hFTD2XX, "FT_GetComPortNumber"); lpfn_FT_Purge = (LPFN_FT_Purge) GetProcAddress(hFTD2XX, "FN_FT_Purge"); } return status = FT_OK; } void WINAPI FT_Finalise(void) { if (hFTD2XX) { FreeLibrary(hFTD2XX); hFTD2XX = NULL; } } FTD2XX_API FT_STATUS FT_ListDevices(PVOID pvArg1, PVOID pvArg2, DWORD dwFlags) { return status = (lpfn_FT_ListDevices ? lpfn_FT_ListDevices(pvArg1, pvArg2, dwFlags) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_Open(int iDevice, FT_HANDLE *ftHandle) { return status = (lpfn_FT_Open ? lpfn_FT_Open(iDevice, ftHandle) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_OpenEx(PVOID pArg1, DWORD Flags, FT_HANDLE *pHandle) { return status = (lpfn_FT_OpenEx ? lpfn_FT_OpenEx(pArg1, Flags, pHandle) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_Close(FT_HANDLE ftHandle) { return status = (lpfn_FT_Close ? lpfn_FT_Close(ftHandle) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_SetTimeouts(FT_HANDLE ftHandle, DWORD dwReadTimeout, DWORD dwWriteTimeout) { return status = (lpfn_FT_SetTimeouts ? lpfn_FT_SetTimeouts(ftHandle, dwReadTimeout, dwWriteTimeout) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_Read(FT_HANDLE ftHandle, LPVOID lpBuffer, DWORD dwBytesToRead, LPDWORD lpBytesReturned) { return status = (lpfn_FT_Read ? lpfn_FT_Read(ftHandle, lpBuffer, dwBytesToRead, lpBytesReturned) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_Write(FT_HANDLE ftHandle, LPVOID lpBuffer, DWORD dwBytesToWrite, LPDWORD lpBytesWritten) { return status = (lpfn_FT_Write ? lpfn_FT_Write(ftHandle, lpBuffer, dwBytesToWrite, lpBytesWritten) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_SetBaudRate(FT_HANDLE ftHandle, ULONG BaudRate) { return status = (lpfn_FT_SetBaudRate ? lpfn_FT_SetBaudRate(ftHandle, BaudRate) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_SetDivisor(FT_HANDLE ftHandle, USHORT usDivisor) { return status = (lpfn_FT_SetDivisor ? lpfn_FT_SetDivisor(ftHandle, usDivisor) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_SetDataCharacteristics(FT_HANDLE ftHandle, UCHAR WordLength, UCHAR StopBits, UCHAR Parity) { return status = (lpfn_FT_SetDataCharacteristics ? lpfn_FT_SetDataCharacteristics(ftHandle, WordLength, StopBits, Parity) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_SetFlowControl(FT_HANDLE ftHandle, USHORT FlowControl, UCHAR XonChar, UCHAR XoffChar) { return status = (lpfn_FT_SetFlowControl ? lpfn_FT_SetFlowControl(ftHandle, FlowControl, XonChar, XoffChar) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_SetDtr(FT_HANDLE ftHandle) { return status = (lpfn_FT_SetDtr ? lpfn_FT_SetDtr(ftHandle) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_ClrDtr(FT_HANDLE ftHandle) { return status = (lpfn_FT_ClrDtr ? lpfn_FT_ClrDtr(ftHandle) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_SetRts(FT_HANDLE ftHandle) { return status = (lpfn_FT_SetRts ? lpfn_FT_SetRts(ftHandle) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_ClrRts(FT_HANDLE ftHandle) { return status = (lpfn_FT_ClrRts ? lpfn_FT_ClrRts(ftHandle) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_SetBitMode(FT_HANDLE ftHandle, UCHAR ucMask, UCHAR ucEnable) { return status = (lpfn_FT_SetBitMode ? lpfn_FT_SetBitMode(ftHandle, ucMask, ucEnable) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_GetBitMode(FT_HANDLE ftHandle, PUCHAR pucMode) { return status = (lpfn_FT_GetBitMode ? lpfn_FT_GetBitMode(ftHandle, pucMode) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_GetComPortNumber(FT_HANDLE ftHandle, LPLONG lplComPortNumber) { return status = (lpfn_FT_GetComPortNumber ? lpfn_FT_GetComPortNumber(ftHandle, lplComPortNumber) : FT_NOT_SUPPORTED); } FTD2XX_API FT_STATUS FT_Purge(FT_HANDLE ftHandle, ULONG Mask) { return status = (lpfn_FT_Purge ? lpfn_FT_Purge(ftHandle, Mask) : FT_NOT_SUPPORTED); } |
【OTA-BOOT】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
/* main.cpp - WPAN OTA Programmer for NXP JN516X Series Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <jendefs.h> #include <AppHardwareApi.h> #include "jn516x.h" #include "wpan.h" // #define TWELITE_CUE #define WDTOUT (1 << 13) // TWELITE-CUE WDTOUT #if defined __cplusplus #define APPSTART extern "C" PUBLIC #else #define APPSTART PUBLIC #endif APPSTART void AppColdStart(void) { u32AHI_Init(); u32AppQApiInit(0, 0, 0); WPan::begin(JN516x::ADDR_OTA_BOOT); #ifdef TWELITE_CUE vAHI_DioSetDirection(0, WDTOUT); #endif while (1) { WPan::handle(); vAHI_WatchdogRestart(); #ifdef TWELITE_CUE vAHI_DioSetOutput(WDTOUT, 0); vAHI_DioSetOutput(0, WDTOUT); #endif } } APPSTART void AppWarmStart(void) { AppColdStart(); } |
【OTA-BRIDGE】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
#include <string.h> #include "device.h" #define ACK 0x06 #define NAK 0x15 #define LED_R 0 // MONOSTICK LED-RED #define LED_Y 1 // MONOSTICK LED-YELLOW static uint16 u16DeviceAddr = JN516x::ADDR_BROADCAST; uint8 csum(void *buf, uint8 len) { uint8 *p = (uint8 *)buf; uint8 c = 0; while (len--) c ^= *p++; return c; } void WPanRecieveCallback(uint16 u16Addr, const uint8 *pu8Data, uint8 u8Len) { if (u16Addr == u16DeviceAddr) { uint8 packet[WPAN_MAX_PAYLOAD_SIZE + 2]; packet[0] = u8Len + 1; memcpy(packet + 1, pu8Data, u8Len++); packet[u8Len] = csum(packet, u8Len); Serial0.write(packet, u8Len + 1); } } void bridge(void) { // packet[0]: len (n + 4) // packet[1]: addr-hi // packet[2]: addr-lo // packet[3]: command // packet[4]: data (n bytes) // packet[4 + n]: csum if (Serial0.available()) { uint8 n, len, packet[256]; for (len = packet[0] = 0; len <= packet[0]; len += n) { if ((n = Serial0.read(packet + len, packet[0] - len + 1)) == 0) break; } if ((len >= 4) && (csum(packet, len) == 0)) { Serial0.write(ACK); u16DeviceAddr = ((uint16)packet[1] << 8) | packet[2]; if (packet[3] == JN516x::OTA_UPDATE_RETRY) { WPan::reTransmit(u16DeviceAddr); LED::on(LED_R); LED::off(LED_R, 1000); } else { WPan::transmit(u16DeviceAddr, packet + 3, len - 4); LED::toggle(LED_R); LED::off(LED_R, 100); } } else { Serial0.write(NAK); LED::on(LED_R); LED::off(LED_R, 3000); } } } void setup(void) { Serial0.begin(Uart::SPEED_1M, Uart::MODE_8N1, Uart::FLOW_RTS_CTS_LOW); WPan::begin(JN516x::ADDR_OTA_BRIDGE); LED::toggle(LED_Y, 1000); } void loop(void) { bridge(); } |
【OTA対応WPanクラス】
※再送処理は、新たに追加したreTransmit()を実行するだけ。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 |
/* wpan.cpp - Wireless Personal Area Network Library for NXP-JN516x (IEEE802.15.4) Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <string.h> #include <PeripheralRegs.h> #include "jn516x.h" #include "crc32.h" #include "wpan.h" WPan::tsNetwork WPan::sNetwork; #if WPAN_SECURITY_ENABLE static const uint8 SECURITY_KEY_DATA[] = WPAN_SECURITY_KEY_DATA; #endif void WPan::begin(uint16 u16Addr, uint16 u16PanId, CHANNEL u8Channel) { if (!WPan::getSequenceNumber(u16Addr)) return; sNetwork.u16Addr = u16Addr; sNetwork.u16PanId = u16PanId; /* set current channel */ eAppApiPlmeSet((PHY_PibAttr_e)PHY_PIB_ATTR_CURRENT_CHANNEL, u8Channel); /* Set up the MAC handles. Must be called AFTER u32AppQApiInit() */ void *s_pvMac = pvAppApiGetMacHandle(); /* Set Pan ID in PIB (also sets match register in hardware) */ MAC_vPibSetPanId(s_pvMac, u16PanId); /* Set short address in PIB (also sets match registers in hardware) */ MAC_vPibSetShortAddr(s_pvMac, u16Addr); /* Enable receiver to be on when idle */ MAC_vPibSetRxOnWhenIdle(s_pvMac, true, false); sNetwork.psTransmit = 0; for (uint32 i = 0; i < sizeof(sNetwork.sTransmitData) / sizeof(sNetwork.sTransmitData[0]); ++i) { sNetwork.sTransmitData[i].next = sNetwork.psTransmit; sNetwork.psTransmit = sNetwork.sTransmitData + i; sNetwork.psTransmit->data.uParam.sReqData.sFrame.sDstAddr.uAddr.u16Short = WPAN_MAX_DEVICES; } } void WPan::transmit(uint16 u16Addr, const uint8 *pu8Data, uint8 u8Len, uint8 u8Handle) { MAC_McpsSyncCfm_s sMcpsSyncCfm; tsSeqNb *psSeqNb = getSequenceNumber(u16Addr); if (!psSeqNb || (u8Len > WPAN_MAX_PAYLOAD_SIZE)) return; uint8 u8Tx = ++psSeqNb->u8Tx; u8Tx = (u16Addr == WPAN_ADDR_BROADCAST ? u8Tx | 0x80 : u8Tx & ~0x80); tsTransmit *psTransmit = getTransmitData(u16Addr); /* Create frame transmission request */ psTransmit->data.u8Type = MAC_MCPS_REQ_DATA; psTransmit->data.u8ParamLength = sizeof(MAC_McpsReqData_s); /* Set handle so we can match confirmation to request */ psTransmit->data.uParam.sReqData.u8Handle = u8Handle; /* Use short address for source */ vSetMacAddr(psTransmit->data.uParam.sReqData.sFrame.sSrcAddr, sNetwork.u16Addr); /* Use short address for destination */ vSetMacAddr(psTransmit->data.uParam.sReqData.sFrame.sDstAddr, u16Addr); /* Frame requires ack but not security, indirect Transmit or GTS */ psTransmit->data.uParam.sReqData.sFrame.u8TxOptions = u8Handle && (u16Addr != WPAN_ADDR_BROADCAST) ? MAC_TX_OPTION_ACK : 0; /* Copy Data */ uint8 *pu8Payload = psTransmit->data.uParam.sReqData.sFrame.au8Sdu; *pu8Payload++ = u8Tx; if (pu8Data && u8Len) { #if WPAN_SECURITY_ENABLE uint8 data[128]; memcpy(&data[WPAN_SECURITY_AES_MODE], pu8Data, u8Len); pu8Data = data; AES::begin(WPAN_SECURITY_AES_MODE, (uint8 *)SECURITY_KEY_DATA, sizeof(SECURITY_KEY_DATA)); AES::encryption(&data[WPAN_SECURITY_AES_MODE], u8Len, u8Tx, (uint8 *)&sNetwork.u16Addr, sizeof(sNetwork.u16Addr), data); u8Len += WPAN_SECURITY_AES_MODE; #endif for (uint8 i = 0; i < u8Len; i++) *pu8Payload++ = *pu8Data++; } /* Set frame length */ psTransmit->data.uParam.sReqData.sFrame.u8SduLength = pu8Payload - psTransmit->data.uParam.sReqData.sFrame.au8Sdu; /* Request Transmit */ vAppApiMcpsRequest(&psTransmit->data, &sMcpsSyncCfm); } void WPan::reTransmit(uint16 u16Addr) { MAC_McpsSyncCfm_s sMcpsSyncCfm; tsTransmit *psTransmit = getTransmitData(u16Addr, false); if (psTransmit) vAppApiMcpsRequest(&psTransmit->data, &sMcpsSyncCfm); } void WPan::handle(void) { MAC_MlmeDcfmInd_s *psMlmeInd; MAC_McpsDcfmInd_s *psMcpsInd; AppQApiHwInd_s*psAHI_Ind; /* Check for anything on the MLME upward queue */ if ((psMlmeInd = psAppQApiReadMlmeInd()) != NULL) { vProcessIncomingMlme(psMlmeInd); vAppQApiReturnMlmeIndBuffer(psMlmeInd); }; /* Check for anything on the MCPS upward queue */ if ((psMcpsInd = psAppQApiReadMcpsInd()) != NULL) { vProcessIncomingMcps(psMcpsInd); vAppQApiReturnMcpsIndBuffer(psMcpsInd); }; /* Check for anything on the AHI upward queue */ if ((psAHI_Ind = psAppQApiReadHwInd()) != NULL) { vProcessIncomingHwEvent(psAHI_Ind); vAppQApiReturnHwIndBuffer(psAHI_Ind); }; } uint16 WPan::address(void) { return sNetwork.u16Addr; } void WPan::transmissionPower(TXPOWER txpower) { // n input range of -32 to 31 dBm // For JN5168, JN5164 and JN5161, it is mapped to one of four levels: // -32, -20, -9 and 0 dBm // For JN5169, it is mapped to the nearest of 26 levels in the range: // -32 to 10 dBm eAppApiPlmeSet((PHY_PibAttr_e)PHY_PIB_ATTR_TX_POWER, txpower); #if E_AHI_ADC_SRC_ADC_5 vAHI_RadioSetReducedInputPower(txpower <= 0); #endif } void WPan::vProcessIncomingMlme(MAC_MlmeDcfmInd_s *psMlmeInd) { } void WPan::vProcessIncomingMcps(MAC_McpsDcfmInd_s *psMcpsInd) { /* Only handle incoming data events one device has been started as a coordinator */ switch(psMcpsInd->u8Type) { /* Incoming data frame */ case MAC_MCPS_IND_DATA: vHandleMcpsDataInd(psMcpsInd->uParam.sIndData.sFrame); break; /* Incoming acknowledgement or ack timeout */ case MAC_MCPS_DCFM_DATA: vHandleMcpsDataDcfm(psMcpsInd->uParam.sDcfmData); break; } } void WPan::vHandleMcpsDataInd(MAC_RxFrameData_s& sFrame) { if ((sFrame.sSrcAddr.u8AddrMode == 2) && (sFrame.u8SduLength > 0)) { uint16 u16Addr = sFrame.sSrcAddr.uAddr.u16Short; tsSeqNb *psSeqNb = getSequenceNumber(u16Addr); if (psSeqNb) { uint8 *pu8Sdu = sFrame.au8Sdu + 1; uint8 u8SduLen = sFrame.u8SduLength - 1; #if WPAN_SECURITY_ENABLE if (u8SduLen) { uint8 data[128]; memcpy(data, pu8Sdu, u8SduLen); pu8Sdu = &data[WPAN_SECURITY_AES_MODE]; u8SduLen -= WPAN_SECURITY_AES_MODE; AES::begin(WPAN_SECURITY_AES_MODE, (uint8 *)SECURITY_KEY_DATA, sizeof(SECURITY_KEY_DATA)); if (!AES::decryption(pu8Sdu, u8SduLen, sFrame.au8Sdu[0], (uint8 *)&u16Addr, sizeof(u16Addr), data)) return; // security failed. } #endif tsTransmit *psTransmit = getTransmitData(u16Addr, false); if (psSeqNb->u8Rx != sFrame.au8Sdu[0]) { /* new packet */ psSeqNb->u8Rx = sFrame.au8Sdu[0]; /* remove transmit data */ removeTransmitData(psTransmit); /* process received packet */ if ((u16Addr == JN516x::ADDR_OTA_BRIDGE) || (u16Addr == JN516x::ADDR_OTA_BRIDGE2)) OTARecieveCallback(u16Addr, pu8Sdu, u8SduLen); else if (WPanRecieveCallback) WPanRecieveCallback(u16Addr, pu8Sdu, u8SduLen); } else if (psTransmit && (sFrame.sDstAddr.uAddr.u16Short != WPAN_ADDR_BROADCAST)) { /* If it is not a broadcast packet, the last transmitted data will be retransmitted. */ MAC_McpsSyncCfm_s sMcpsSyncCfm; vAppApiMcpsRequest(&psTransmit->data, &sMcpsSyncCfm); } } } } void WPan::vHandleMcpsDataDcfm(MAC_McpsCfmData_s& sDcfmData) { OTATransmitCallback(sDcfmData.u8Handle, sDcfmData.u8Status); if (WPanTransmitCallback) WPanTransmitCallback(sDcfmData.u8Handle, sDcfmData.u8Status); } void WPan::vProcessIncomingHwEvent(AppQApiHwInd_s *psAHI_Ind) { if (WPanHWEventCallback) WPanHWEventCallback(psAHI_Ind->u32DeviceId, psAHI_Ind->u32ItemBitmap); } WPan::tsTransmit *WPan::getTransmitData(uint16 u16Addr, bool alloc) { tsTransmit **p, *q; for (p = &sNetwork.psTransmit; *p; p = &(*p)->next) { if ((alloc && !(*p)->next) || ((*p)->data.uParam.sReqData.sFrame.sDstAddr.uAddr.u16Short == u16Addr)) { *p = (q = *p)->next; q->next = sNetwork.psTransmit; sNetwork.psTransmit = q; return q; } } return 0; } void WPan::removeTransmitData(tsTransmit *psTransmit) { tsTransmit **p; if (psTransmit) { for (p = &sNetwork.psTransmit;; p = &(*p)->next) { if (*p == psTransmit) { *p = psTransmit->next; psTransmit->next = 0; psTransmit->data.uParam.sReqData.sFrame.sDstAddr.uAddr.u16Short = WPAN_MAX_DEVICES; } if (!(*p)->next) { (*p)->next = psTransmit; break; } } } } WPan::tsSeqNb *WPan::getSequenceNumber(uint16 u16Addr) { return u16Addr < WPAN_MAX_DEVICES ? sNetwork.sSeqNb + u16Addr : (u16Addr >= (uint16)-WPAN_RSV_ADDRESS ? sNetwork.sSeqNb + WPAN_MAX_DEVICES + WPAN_RSV_ADDRESS + (int16)u16Addr : 0); } void WPan::vSetMacAddr(MAC_Addr_s& sAddr, uint16 u16Addr) { sAddr.u8AddrMode = 2; sAddr.u16PanId = sNetwork.u16PanId; sAddr.uAddr.u16Short = u16Addr; } void WPan::write32(uint8 *buf, uint32 data) { buf[3] = (uint8)(data >> 0); buf[2] = (uint8)(data >> 8); buf[1] = (uint8)(data >> 16); buf[0] = (uint8)(data >> 24); } uint32 WPan::read32(const uint8 *buf) { return ((uint32)buf[0] << 24) | ((uint32)buf[1] << 16) | ((uint16)buf[2] << 8) | ((uint8 )buf[3] << 0); } void WPan::OTARecieveCallback(uint16 u16Addr, const uint8 *pu8Data, uint8 u8Len) { #if defined(JN5179) JN516x::tsFlashHeader_JN5179 sFlashHeader; #else JN516x::tsFlashHeader sFlashHeader; #endif uint32 u32Remap; uint8 u8Sector; uint8 u8Ack[16] = { *pu8Data++, JN516x::OTA_STATUS_OK }; uint8 u8AckLen = 2; uint8 u8Handle = 0; --u8Len; switch (u8Ack[0]) { case JN516x::OTA_UPDATE_CHIPVER: u32Remap = u32REG_SysRead(REG_SYS_FLASH_REMAP); u8Sector = JN516x::chipFlashSectors(CHIP_VERSION) - 1; if (u8Sector < 8) vREG_SysWrite(REG_SYS_FLASH_REMAP , (u32Remap & ~(0x0F << ((u8Sector & 7) << 2))) | (u8Sector << ((u8Sector & 7) << 2))); #if defined(JN5169) || defined(JN5179) else { u32Remap = u32REG_SysRead(REG_SYS_FLASH_REMAP2); vREG_SysWrite(REG_SYS_FLASH_REMAP2, (u32Remap & ~(0x0F << ((u8Sector & 7) << 2))) | (u8Sector << ((u8Sector & 7) << 2))); } #endif if (!FlashInit()) u8Ack[1] = JN516x::OTA_STATUS_SDK_ERROR; else if (!bAHI_FullFlashRead(FLASH_SECTOR_OFFSET(u8Sector), sizeof(sFlashHeader), (uint8 *)&sFlashHeader)) u8Ack[1] = JN516x::OTA_STATUS_SDK_ERROR; else { // check OTA-BOOT if (u8Sector == (u32Remap & 0x0F)) sNetwork.bOtaValid = true; else if (sFlashHeader.imageSize <= FLASH_SECTOR_OFFSET(u8Sector - (u32Remap & 0x0F))) { sNetwork.bOtaValid = false; sNetwork.bOtaValid = memcmp(sFlashHeader.sBIR.magicNumber, JN516x::MAGICNUMBER, sizeof(JN516x::MAGICNUMBER)) == 0; #if defined(JN5179) sNetwork.bOtaValid |= memcmp(sFlashHeader.sBIR.magicNumber, JN516x::MAGICNUMBER_JN5179, sizeof(JN516x::MAGICNUMBER)) == 0; #endif sNetwork.bOtaValid &= sFlashHeader.sBIR.status == 0x01; sNetwork.bOtaValid &= sFlashHeader.sBIR.applicationID == 0x0000; } write32(u8Ack + 2, CHIP_VERSION); u8Ack[6] = sNetwork.bOtaValid; u8AckLen = 7; } break; case JN516x::OTA_UPDATE_BLDMODE: u8Sector = (u8Len && (pu8Data[0] == 0xBF) ? 0xBF : 0xFF); if (sNetwork.bOtaValid || (u8Sector == 0xBF)) sNetwork.u8OtaHandle = u8Handle = u8Sector; else u8Ack[1] = JN516x::OTA_STATUS_BLD_ERROR; break; case JN516x::OTA_UPDATE_START: u8Sector = u32REG_SysRead(REG_SYS_FLASH_REMAP) & 0x0F; if (u8Sector && (u8Sector != JN516x::chipFlashSectors(CHIP_VERSION) - 1)) u8Ack[1] = JN516x::OTA_STATUS_BLD_ERROR; else if (!FlashInit()) u8Ack[1] = JN516x::OTA_STATUS_SDK_ERROR; else { if (u8Sector) { vREG_SysWrite(REG_SYS_FLASH_REMAP , 0x65432100U | (u32REG_SysRead(REG_SYS_FLASH_REMAP) & 0x0F)); #if defined(JN5169) || defined(JN5179) vREG_SysWrite(REG_SYS_FLASH_REMAP2, 0xEDCBA987U); #endif sNetwork.u32OtaStart = FLASH_SECTOR_OFFSET(1); } else { vREG_SysWrite(REG_SYS_FLASH_REMAP , 0x76543210U); #if defined(JN5169) || defined(JN5179) vREG_SysWrite(REG_SYS_FLASH_REMAP2, 0xFEDCBA98U); #endif sNetwork.u32OtaStart = FLASH_SECTOR_OFFSET(JN516x::chipFlashSectors(CHIP_VERSION) - 1); } sNetwork.u32OtaAddr = sNetwork.u32OtaStart; sNetwork.u8OtaErase = 0xFF; sNetwork.u8OtaHandle = 0; CRC32::init(); } break; case JN516x::OTA_UPDATE_PROGRAM: CRC32::update(pu8Data, u8Len); if (sNetwork.u32OtaAddr == sNetwork.u32OtaStart) { memcpy(sNetwork.u8OtaHeader, pu8Data, sizeof(sNetwork.u8OtaHeader)); sNetwork.u32OtaAddr += sizeof(sNetwork.u8OtaHeader); pu8Data += sizeof(sNetwork.u8OtaHeader); u8Len -= sizeof(sNetwork.u8OtaHeader); } u8Sector = (sNetwork.u32OtaAddr + (u8Len ? u8Len - 1 : 0)) >> 15; if (sNetwork.u8OtaErase != u8Sector) { sNetwork.u8OtaErase = u8Sector; if (!bAHI_FlashEraseSector(u8Sector)) { u8Ack[1] = JN516x::OTA_STATUS_SDK_ERROR; break; } } if (!bAHI_FullFlashProgram(sNetwork.u32OtaAddr, u8Len, (uint8 *)pu8Data)) u8Ack[1] = JN516x::OTA_STATUS_SDK_ERROR; else sNetwork.u32OtaAddr += u8Len; break; case JN516x::OTA_UPDATE_END: if (CRC32::result() == read32(pu8Data)) sNetwork.u8OtaHandle = u8Handle = 0xFE; else { u8Ack[1] = JN516x::OTA_STATUS_CRC_ERROR; write32(u8Ack + 2, CRC32::result()); u8AckLen = 6; } break; default: u8Ack[1] = JN516x::OTA_STATUS_ARG_ERROR; break; } transmit(u16Addr, u8Ack, u8AckLen, u8Handle); } void WPan::OTATransmitCallback(uint8 u8Handle, uint8 u8Status) { if (sNetwork.u8OtaHandle && (sNetwork.u8OtaHandle == u8Handle)) { sNetwork.u8OtaHandle = 0; if (u8Status == 0) { switch (u8Handle) { case 0xFF: if ((u32REG_SysRead(REG_SYS_FLASH_REMAP) & 0x0F) != JN516x::chipFlashSectors(CHIP_VERSION) - 1) { if (WPanOTAStartCallback) WPanOTAStartCallback(); disabeApp(); vAHI_SwReset(); } break; case 0xFE: if (bAHI_FullFlashProgram(sNetwork.u32OtaStart, sizeof(sNetwork.u8OtaHeader), sNetwork.u8OtaHeader)) vAHI_SwReset(); break; } } } } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" void WPan::disabeApp(void) { uint8 u8Buf[32]; if (bAHI_FullFlashRead(0, sizeof(u8Buf), u8Buf)) { #if defined(JN5179) ((JN516x::tsFlashHeader_JN5179 *)u8Buf)->sBIR.status = 0; #else ((JN516x::tsFlashHeader *)u8Buf)->sBIR.status = 0; #endif bAHI_FullFlashProgram(0, sizeof(u8Buf), u8Buf); } } #pragma GCC diagnostic pop bool WPan::FlashInit(void) { return bAHI_FlashInit(E_FL_CHIP_AUTO, 0); } |
【関連投稿】
NXP JN516X (TWELITE) をプログラミングする(開発環境の構築)
NXP JN516X (TWELITE) をプログラミングする(メイン・ルーチン)
NXP JN516X (TWELITE) をプログラミングする(TICKTIMER)
NXP JN516X (TWELITE) をプログラミングする(UART)
NXP JN516X (TWELITE) をプログラミングする(SYSTEM)
NXP JN516X (TWELITE) をプログラミングする(GPIO)
NXP JN516X (TWELITE) をプログラミングする(TIMER)
NXP JN516X (TWELITE) をプログラミングする(ALARM)
NXP JN516X (TWELITE) をプログラミングする(WAKETIMER)
NXP JN516X (TWELITE) をプログラミングする(WATCHDOG)
NXP JN516X (TWELITE) をプログラミングする(I2C)
NXP JN516X (TWELITE) をプログラミングする(SPI)
NXP JN516X (TWELITE) をプログラミングする(ADC)
NXP JN516X (TWELITE) をプログラミングする(COMPARATOR)
NXP JN516X (TWELITE) をプログラミングする(CLOCK)
NXP JN516X (TWELITE) をプログラミングする(BROWNOUT)
NXP JN516X (TWELITE) をプログラミングする(PULSCOUNTER)
NXP JN516X (TWELITE) をプログラミングする(INFRARED)
NXP JN516X (TWELITE) をプログラミングする(RANDOM-GENERATOR)
NXP JN516X (TWELITE) をプログラミングする(FLASH)
NXP JN516X (TWELITE) をプログラミングする(EEPROM)
NXP JN516X (TWELITE) をプログラミングする(WPAN)
NXP JN516X (TWELITE) をプログラミングする(Eclipse-CDT+MWSTAGE)
NXP JN516X (TWELITE) をプログラミングする(乗算と除算)
NXP JN516X (TWELITE) をプログラミングする(マルチタスク)
NXP JN516X (TWELITE) をプログラミングする(フラッシュ・プログラマー)
NXP JN516X (TWELITE) をプログラミングする(OTA UPDATE)
NXP JN516X (TWELITE) をプログラミングする(TWELITE CUE/MC3630)
NXP JN516X (TWELITE) をプログラミングする(LED)
NXP JN516X (TWELITE) をプログラミングする(AES)
NXP JN516X (TWELITE) をプログラミングする(Downloads)