]> cloudbase.mooo.com Git - z180-stamp.git/blob - avr/env.c
b45f0af948e701b4627b6ed2579d137094145f77
[z180-stamp.git] / avr / env.c
1 /*
2 * (C) Copyright 2014 Leo C. <erbl259-lmu@yahoo.de>
3 *
4 * SPDX-License-Identifier: GPL-2.0
5 */
6
7 #include "common.h"
8 #include <string.h>
9 #include <stdlib.h>
10 #include <stdbool.h>
11 #include <avr/eeprom.h>
12
13 #include "config.h"
14 #include "debug.h"
15 #include "xmalloc.h"
16 #include "crc.h"
17 #include "command.h"
18 #include "env.h"
19
20
21 #define ENV_SIZE (CONFIG_ENV_SIZE - sizeof(uint16_t) -1)
22 #define ACTIVE_FLAG 1
23 #define OBSOLETE_FLAG 0
24
25 #define ENVLIST_DELETE (1<<0)
26
27
28 /*
29 * Default Environment
30 */
31
32 #define DELIM "\0"
33
34 const FLASH char default_env[] = {
35 ENV_BAUDRATE "=" "115200" DELIM
36 ENV_BOOTDELAY "=" "3" DELIM
37 ENV_BOOTCMD "=" "pin ${pins}; loadcpm3; go ${startaddress}" DELIM
38 ENV_CPM3_SYSFILE "=" CONFIG_CPM3_SYSFILE DELIM
39 ENV_PINALIAS "=" "0:PG5,1:PG4,2:PB4,3:PB5,4:PB6,5:PB7,"
40 "6:PG3,7:PG2,8:PG1,9:PG0,10:PE7" DELIM
41 ENV_STARTADDRESS "=" "0" DELIM
42 "pins" "=" "2,8 low 9 high 3 2" DELIM
43 DELIM
44 };
45
46
47 /* EEPROM storage */
48 typedef struct environment_s {
49 uint16_t crc; /* CRC16 over data bytes */
50 uint8_t flags; /* active/obsolete flags */
51 char data[ENV_SIZE]; /* Environment data */
52 } env_t;
53
54
55 /* */
56 typedef struct env_item_s {
57 char * envvar;
58 } env_item_t;
59
60
61 static uint8_t env_valid;
62 static env_item_t env_list[CONFIG_ENVVAR_MAX];
63 static int entrycount;
64
65
66 static
67 char env_get_char(uint16_t index)
68 {
69 unsigned int off = CONFIG_ENV_OFFSET;
70 char ret;
71
72 switch (env_valid) {
73 case 2:
74 off += CONFIG_ENV_SIZE;
75 case 1:
76 ret = (char) eeprom_read_byte((const uint8_t *)off + index +
77 offsetof(env_t, data));
78 break;
79
80 default:
81 ret = default_env[index];
82 }
83
84 return ret;
85 }
86
87
88 static const FLASH char *comp_key;
89
90 static
91 int comp_env_items(const void *m1, const void *m2)
92 {
93 env_item_t *ep1 = (env_item_t *) m1;
94 env_item_t *ep2 = (env_item_t *) m2;
95
96 if (ep1 == NULL)
97 return - strcmp_P(ep2->envvar, comp_key);
98 else
99 return strcmp(ep1->envvar, ep2->envvar);
100 }
101
102
103 env_item_t *envlist_search(const MEMX char *name)
104 {
105 #ifdef __MEMX
106 if (__builtin_avr_flash_segment(name) != -1) {
107 comp_key = name;
108 return bsearch(0, env_list, entrycount,
109 sizeof(env_item_t), comp_env_items);
110 } else {
111
112 env_item_t e;
113 e.envvar = (char *) name;
114
115 return bsearch(&e, env_list, entrycount,
116 sizeof(env_item_t), comp_env_items);
117 }
118 #else
119 env_item_t e;
120 e.envvar = (char *) name;
121
122 return bsearch(&e, env_list, entrycount,
123 sizeof(env_item_t), comp_env_items);
124 #endif /* __MEMX */
125 }
126
127
128 static
129 env_item_t *envlist_enter(env_item_t *e)
130 {
131 const size_t size = sizeof(env_item_t);
132 env_item_t *ep;
133
134 ep = bsearch(e, env_list, entrycount,
135 size, comp_env_items);
136
137 if (ep == NULL) {
138 if (entrycount < CONFIG_ENVVAR_MAX) {
139
140 env_list[entrycount++] = *e;
141 qsort(env_list, entrycount, size, comp_env_items);
142 ep = bsearch(e, env_list, entrycount,
143 size, comp_env_items);
144 }
145 } else {
146 free(ep->envvar);
147 ep->envvar = e->envvar;
148 }
149
150 return ep;
151 }
152
153
154 static
155 int env_item_delete(env_item_t *ep)
156 {
157 if (entrycount == 0)
158 return -1;
159
160 free(ep->envvar);
161
162 entrycount--;
163 size_t size = sizeof(env_item_t);
164 memmove(ep, ep + 1, (env_list - ep)*size + entrycount*size);
165
166 return 0;
167 }
168
169 static
170 int envlist_delete(const MEMX char *name)
171 {
172 env_item_t *ep = envlist_search(name);
173
174 if (ep != NULL)
175 return env_item_delete(ep);
176
177 return 1;
178 }
179
180
181
182 static
183 int envlist_import(uint8_t flags)
184 {
185 uint16_t index;
186
187 int len;
188 env_item_t e;
189 char *np, c;
190 uint_fast8_t ef;
191
192 if ((flags & ENVLIST_DELETE) != 0)
193 while (entrycount != 0)
194 env_item_delete(&env_list[entrycount-1]);
195
196 for (index = 0; env_get_char(index) != '\0'; ) {
197 for (len = 0; env_get_char(index + len) != '\0'; ++len) {
198 if ((index + len) >= ENV_SIZE)
199 return -1;
200 }
201
202 np = (char *) xmalloc(len+1);
203 if (np == NULL) {
204 printf_P(PSTR("## Can't malloc %d bytes\n"), len+1);
205 return 1;
206 }
207 e.envvar = np;
208 ef = 0;
209 while ((c = env_get_char(index++)) != '\0') {
210 if (!ef && (c == '=')) {
211 *np = '\0';
212 ef = 1;
213 } else
214 *np = c;
215 np++;
216 }
217 *np = '\0';
218 envlist_enter(&e);
219 }
220
221
222 return 0;
223 }
224
225
226 static
227 uint16_t env_crc(uint16_t data_offset)
228 {
229 uint16_t crc;
230 uint16_t i;
231 char c, c0;
232
233 crc = 0xffff;
234 c = 0xff;
235 for (i = 0; !(c == 0 && c0 == 0) && i < ENV_SIZE; i++)
236 {
237 c0 = c;
238 c = eeprom_read_byte((const uint8_t *) data_offset + i);
239 crc = crc16(crc, c);
240 }
241 return crc ;
242 }
243
244
245 /**
246 * return valid env
247 */
248 static
249 int env_check_valid(void)
250 {
251 const uint16_t offset[2] = {CONFIG_ENV_OFFSET,
252 CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE};
253 uint_fast8_t flags[2], crc_ok[2];
254 int rc;
255
256 /* read FLAGS */
257 flags[0] = eeprom_read_byte ((uint8_t *) offset[0] +
258 offsetof(env_t, flags));
259 flags[1] = eeprom_read_byte ((uint8_t *) offset[1] +
260 offsetof(env_t, flags));
261
262 /* check CRC */
263 crc_ok[0] = (
264 eeprom_read_word((uint16_t *) offset[0] +
265 offsetof(env_t, crc))
266 == env_crc(offset[0] + offsetof(env_t, data))
267 );
268 crc_ok[1] = (
269 eeprom_read_word((uint16_t *) offset[1] +
270 offsetof(env_t, crc))
271 == env_crc(offset[1] + offsetof(env_t, data))
272 );
273
274 if (!crc_ok[0] && !crc_ok[1]) {
275 rc = 0;
276
277 } else if (crc_ok[0] && !crc_ok[1]) {
278 rc = 1;
279 } else if (!crc_ok[0] && crc_ok[1]) {
280 rc = 2;
281 } else {
282 /* both ok - check serial */
283 #if 1
284 if (flags[1] == ACTIVE_FLAG && flags[0] != ACTIVE_FLAG)
285 rc = 2;
286 else if (flags[1] == OBSOLETE_FLAG && flags[0] == 0xFF)
287 rc = 2;
288 else
289 rc = 1;
290 #else
291 if (flags[0] == ACTIVE_FLAG && flags[1] == OBSOLETE_FLAG)
292 rc = 1;
293 else if (flags[0] == OBSOLETE_FLAG && flags[1] == ACTIVE_FLAG)
294 rc = 2;
295 else if (flags[0] == 0xFF && flags[1] == 0)
296 rc = 2;
297 else if (flags[1] == 0xFF && flags[0] == 0)
298 rc = 1;
299 else /* flags are equal - almost impossible */
300 rc = 1;
301 #endif
302 }
303
304 return rc;
305 }
306
307
308 int env_init(void)
309 {
310 env_valid = env_check_valid();
311 if (env_valid == 0) {
312 printf_P(PSTR("*** Warning - bad CRC, "
313 "using default environment\n\n"));
314 }
315
316 envlist_import(ENVLIST_DELETE);
317 return 0;
318 }
319
320
321 char *getenv_str(const MEMX char *name)
322 {
323 env_item_t *ep;
324 char *ret = NULL;
325
326 ep = envlist_search(name);
327 if (ep != NULL)
328 ret = ep->envvar + strlen(ep->envvar) +1;
329 return ret;
330 }
331
332 static
333 int env_item_save(env_item_t *ep, uint16_t offset, int space_left)
334 {
335 int nlen, vlen;
336 char *var = ep->envvar;
337
338 nlen = strlen(var);
339 if (nlen == 0)
340 return 0;
341 vlen = strlen(var + nlen + 1);
342 if (vlen == 0)
343 return 0;
344 if (nlen + vlen + 2 > space_left)
345 return 0;
346
347 eeprom_update_block(var, (uint8_t *) offset, nlen);
348 offset += nlen;
349 eeprom_update_byte((uint8_t *) offset++, '=');
350 eeprom_update_block(var + nlen +1, (uint8_t *) offset, vlen+1);
351
352 return nlen + vlen + 2;
353 }
354
355
356 static
357 int saveenv(void)
358 {
359 unsigned int off = CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE;
360 unsigned int off_red = CONFIG_ENV_OFFSET;
361 unsigned int pos;
362 int len, left;
363 uint16_t crc;
364 int rc = 0;
365
366 if (env_valid == 2) {
367 off = CONFIG_ENV_OFFSET;
368 off_red = CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE;
369 }
370
371 eeprom_update_byte((uint8_t *) off + offsetof(env_t, flags), 0xff);
372
373 pos = off + offsetof(env_t, data);
374 left = ENV_SIZE - 1;
375 for (int i = 0 ; i < entrycount; i++) {
376 len = env_item_save(&env_list[i], pos, left);
377 if (len == 0) {
378 return 1;
379 }
380 pos += len;
381 left -= len;
382 }
383 /* terminate list */
384 eeprom_update_byte((uint8_t *) pos, 0);
385 crc = env_crc(off + offsetof(env_t, data));
386 eeprom_update_word((uint16_t *) off + offsetof(env_t, crc), crc);
387 eeprom_update_byte((uint8_t *) off + offsetof(env_t, flags),
388 ACTIVE_FLAG);
389
390 if (rc == 0) {
391 eeprom_update_byte((uint8_t *) off_red + offsetof(env_t, flags),
392 OBSOLETE_FLAG);
393 env_valid = (env_valid == 2) ? 1 : 2;
394 }
395
396 return rc;
397 }
398
399
400 static
401 int env_item_print(env_item_t *ep, bool mode)
402 {
403 int len;
404 char *ev = ep->envvar;
405
406 if (mode) {
407 len = printf_P(PSTR("setenv %s "), ev) - 7;
408 len += printf_P(PSTR("'%s'\n"), ev + len) - 2;
409 } else {
410 len = printf_P(PSTR("%s="), ev);
411 len += printf_P(PSTR("%s\n"), ev + len);
412 }
413 return len;
414 }
415
416
417 /*
418 * Command interface: print one or all environment variables
419 *
420 * Returns -1 in case of error, or length of printed string
421 */
422 static
423 int env_print(const MEMX char *name, bool mode)
424 {
425 int len = -1;
426
427 if (name) { /* print a single name */
428
429 env_item_t *ep = envlist_search(name);
430 if (ep != NULL)
431 len = env_item_print(ep, mode);
432
433 } else { /* print whole list */
434 len = 0;
435 for (int i = 0 ; i < entrycount; i++) {
436 len += env_item_print(&env_list[i], mode);
437 }
438 }
439 return len;
440 }
441
442
443 /**
444 * Set or delete environment variable
445 *
446 * Set a new environment variable,
447 * or replace or delete an existing one.
448 *
449 * @param flag (not used)
450 * @param argc
451 * @param argv[1] Environment variable to set or delete
452 * if no more args
453 * @param argv[2] ... Value to set it to
454 *
455 * @return 0 if ok, 1 on error
456 */
457 static
458 command_ret_t _do_env_set(int flag, int argc, char * const argv[])
459 {
460 int i, len;
461 char *name, *value, *valp, *p;
462 env_item_t e, *ep;
463
464 (void) flag;
465
466 name = argv[1];
467 value = argv[2];
468
469 if (strchr(name, '=')) {
470 printf_P(PSTR("## Error: illegal character '='"
471 "in variable name \"%s\"\n"), name);
472 return CMD_RET_FAILURE;
473 }
474 len = strlen(name);
475 if (len > CONFIG_SYS_ENV_NAMELEN) {
476 printf_P(PSTR("## Error: Variable name \"%s\" too long. "
477 "(max %d characters)\n"), name, CONFIG_SYS_ENV_NAMELEN);
478 return CMD_RET_FAILURE;
479 }
480 /*
481 env_id++;
482 */
483 /* Delete only ? */
484 if (argc < 3 || argv[2] == NULL) {
485 int rc = envlist_delete(name);
486 return rc ? CMD_RET_FAILURE : CMD_RET_SUCCESS;
487 }
488
489 /*
490 * Insert / replace new value
491 */
492 for (i = 2, len += 1; i < argc; ++i)
493 len += strlen(argv[i]) + 1;
494
495 value = xmalloc(len);
496 if (value == NULL) {
497 printf_P(PSTR("## Can't malloc %d bytes\n"), len);
498 return CMD_RET_FAILURE;
499 }
500 strcpy(value, name);
501 valp = value + strlen(name) + 1;
502 for (i = 2, p = valp; i < argc; ++i) {
503 char *v = argv[i];
504
505 while ((*p++ = *v++) != '\0')
506 ;
507 *(p - 1) = ' ';
508 }
509 if (p != valp)
510 *--p = '\0';
511
512 e.envvar = value;
513 ep = envlist_enter(&e);
514 if (!ep) {
515 printf_P(PSTR("## Error inserting \"%s\" variable.\n"),
516 name);
517 return CMD_RET_FAILURE;
518 }
519
520 return CMD_RET_SUCCESS;
521 }
522
523 /**
524 * Set an environment variable
525 *
526 * @param varname Environment variable to set
527 * @param varvalue Value to set it to
528 * @return 0 if ok, 1 on error
529 */
530 static
531 int setenv(const MEMX char *varname, const char *varvalue)
532 {
533 int rc;
534
535 #ifdef __MEMX
536 char *tmpname = NULL;
537 if (__builtin_avr_flash_segment(varname) != -1) {
538 tmpname = malloc(strlen_P(varname)+1);
539 if (tmpname == NULL) {
540 printf_P(PSTR("setenv: Out of Memory!\n"));
541 return 1;
542 }
543 strcpy_P(tmpname, varname);
544 } else
545 tmpname = (char *) varname;
546 #endif
547
548 const char * const argv[3] = { NULL, tmpname, varvalue };
549 int argc = 3;
550
551 if (varvalue == NULL || varvalue[0] == '\0')
552 --argc;
553
554 rc = (int) _do_env_set(0, argc, (char * const *)argv);
555
556 #ifdef __MEMX
557 free(tmpname);
558 #endif
559 return rc;
560 }
561
562 /**
563 * Set an environment variable to an integer value
564 *
565 * @param name Environment variable to set
566 * @param value Value to set it to
567 * @param radix Base
568 * @return 0 if ok, 1 on error
569 */
570 static
571 int setenv_intval(const MEMX char *name, unsigned long value, int radix)
572 {
573 char buf[11];
574
575 ultoa(value, buf, radix);
576
577 return setenv(name, buf);
578 }
579
580 /**
581 * Set an environment variable to a decimal integer value
582 *
583 * @param name Environment variable to set
584 * @param value Value to set it to
585 * @return 0 if ok, 1 on error
586 */
587 int setenv_ulong(const MEMX char *name, unsigned long value)
588 {
589 return setenv_intval(name, value, 10);
590 }
591
592
593 /**
594 * Set an environment variable to a value in hex
595 *
596 * @param name Environment variable to set
597 * @param value Value to set it to
598 * @return 0 if ok, 1 on error
599 */
600 int setenv_hex(const MEMX char *name, unsigned long value)
601 {
602 return setenv_intval(name, value, 16);
603 }
604
605
606 /**
607 * Decode the integer value of an environment variable and return it.
608 *
609 * @param name Name of environemnt variable
610 * @param base Number base to use (normally 10, or 16 for hex)
611 * @param default_val Default value to return if the variable is not
612 * found
613 * @return the decoded value, or default_val if not found
614 */
615 unsigned long getenv_ulong(const MEMX char *name, int base, unsigned long default_val)
616 {
617 unsigned long value;
618 char *vp, *endp;
619
620 env_item_t *ep = envlist_search(name);
621
622 if (ep != NULL ) {
623 vp = ep->envvar + strlen(ep->envvar) +1;
624 value = strtoul(vp, &endp, base);
625 if (endp != vp)
626 return value;
627 }
628
629 return default_val;
630 }
631
632
633 /*
634 * Read an environment variable as a boolean
635 */
636 bool getenv_yesno(const MEMX char *name)
637 {
638 char *s = getenv_str(name);
639
640 if (s == NULL)
641 return false;
642
643 return strchr_P(PSTR("1yYtT"), *s) != NULL;
644
645 /*
646 return *s == '1' || *s == 'y' || *s == 'Y' || *s == 't' || *s == 'T' ?
647 1 : 0;
648 */
649 }
650
651 command_ret_t do_env_print(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
652 {
653 (void) cmdtp; (void) flag;
654
655 bool mode = 0;
656 command_ret_t rc = CMD_RET_SUCCESS;
657
658 /* reset getopt() */
659 optind = 0;
660
661 int opt;
662 while ((opt = getopt(argc, argv, PSTR("s"))) != -1) {
663 switch (opt) {
664 case 's':
665 mode = 1;
666 break;
667 default: /* '?' */
668 return CMD_RET_USAGE;
669 }
670 }
671
672 if (optind == argc) {
673 /* print all env vars */
674 int size = env_print(NULL, mode);
675 if (size < 0)
676 return CMD_RET_FAILURE;
677 if (mode == 0)
678 printf_P(PSTR("\nEnvironment size: %d/%d bytes\n"),
679 size, ENV_SIZE);
680 return CMD_RET_SUCCESS;
681 }
682
683 /* print selected env vars */
684 while (optind < argc) {
685 int rc = env_print(argv[optind], mode);
686 if (rc < 0) {
687 printf_P(PSTR("## Error: \"%s\" not defined\n"), argv[optind]);
688 rc = CMD_RET_FAILURE;
689 }
690 optind++;
691 }
692
693 return rc;
694 }
695
696
697 command_ret_t do_env_set(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
698 {
699 (void) cmdtp;
700
701 if (argc < 2)
702 return CMD_RET_USAGE;
703
704 return _do_env_set(flag, argc, argv);
705 }
706
707
708 command_ret_t do_env_default(cmd_tbl_t *cmdtp, int flag,
709 int argc, char * const argv[])
710 {
711 (void) cmdtp; (void) flag; (void) argc; (void) argv;
712
713 uint8_t tmp = env_valid;
714 env_valid = 0;
715
716 /* Reset the whole environment */
717 printf_P(PSTR("## Resetting to default environment\n"));
718 envlist_import(ENVLIST_DELETE);
719
720 env_valid = tmp;
721
722 return CMD_RET_SUCCESS;
723 }
724
725
726 command_ret_t do_env_save(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
727 {
728 (void) cmdtp; (void) flag; (void) argc; (void) argv;
729
730 printf_P(PSTR("Saving Environment ...\n"));
731 return saveenv() ? CMD_RET_FAILURE : CMD_RET_SUCCESS;
732 }
733
734
735 #if defined(CONFIG_AUTO_COMPLETE)
736 int env_complete(char *var, int maxv, char *cmdv[], int bufsz, char *buf)
737 {
738 ENTRY *match;
739 int found, idx;
740
741 idx = 0;
742 found = 0;
743 cmdv[0] = NULL;
744
745 while ((idx = hmatch_r(var, idx, &match, &env_htab))) {
746 int vallen = strlen(match->key) + 1;
747
748 if (found >= maxv - 2 || bufsz < vallen)
749 break;
750
751 cmdv[found++] = buf;
752 memcpy(buf, match->key, vallen);
753 buf += vallen;
754 bufsz -= vallen;
755 }
756
757 qsort(cmdv, found, sizeof(cmdv[0]), strcmp_compar);
758
759 if (idx)
760 cmdv[found++] = "...";
761
762 cmdv[found] = NULL;
763 return found;
764 }
765 #endif