Compare commits

...

4 Commits

Author SHA1 Message Date
Edward Emelianov
aeb5cce6ee refresh my hash 2026-03-07 18:23:37 +03:00
Edward Emelianov
055d7f7f59 fixed, tested 2026-03-07 17:45:48 +03:00
Edward Emelianov
d18ab25440 example of helpcmds.in 2026-03-07 15:12:20 +03:00
Edward Emelianov
524a39b8a2 fixed for new libusefull_macros 2026-03-07 15:08:35 +03:00
8 changed files with 206 additions and 185 deletions

View File

@@ -5,3 +5,16 @@ another files used for test: use script ./run for it
Compile: gcc -lusefull_macro file.c -o file
gcc -lusefull_macro test.c hash.c -o test
file helpcmds.in should be included into proto.c as help list:
const char *helpstring =
"https://github.com/eddyem/stm32samples/tree/master/F3:F303/Multistepper build#" BUILD_NUMBER " @ " BUILD_DATE "\n"
"Format: cmd [N] - getter, cmd [N] = val - setter; N - optional index\n"
"* - command not supported yet, G - getter, S - setter\n\n"
#include "hashgen/helpcmds.in"
;
helpcmds.in format: each string should be in quotes with '\n' @ its end. First word - command, next text - help.

View File

@@ -20,6 +20,8 @@
#include <usefull_macros.h>
#include <ctype.h>
// maximal string length (n*4) without terminating '\0' - for buffers
#define MAXCMDLEN (128)
#define ALLOCSZ (5000)
typedef struct{
@@ -31,35 +33,44 @@ typedef struct{
static glob_pars G = {.headerfile = "hash.h", .sourcefile = "hash.c"};
static int help = 0;
static myoption cmdlnopts[] = {
static sl_option_t cmdlnopts[] = {
{"help", NO_ARGS, NULL, 'h', arg_int, APTR(&help), "show this help"},
{"dict", NEED_ARG, NULL, 'd', arg_string, APTR(&G.dict), "dictionary file"},
{"header", NEED_ARG, NULL, 'H', arg_string, APTR(&G.headerfile),"output header filename"},
{"source", NEED_ARG, NULL, 'S', arg_string, APTR(&G.sourcefile),"output source filename"},
{"genfunc", NO_ARGS, NULL, 'F', arg_int, APTR(&G.genfunc), "generate function bodys"},
{"genfunc", NO_ARGS, NULL, 'F', arg_int, APTR(&G.genfunc), "generate function bodies"},
end_option
};
static void parse_args(int argc, char **argv){
parseargs(&argc, &argv, cmdlnopts);
if(help) showhelp(-1, cmdlnopts);
sl_parseargs(&argc, &argv, cmdlnopts);
if(help) sl_showhelp(-1, cmdlnopts);
if(argc > 0){
red("Unused arguments:\n");
for(int i = 0; i < argc; ++i)
printf("%s ", argv[i]);
printf("\n");
showhelp(-1, cmdlnopts);
sl_showhelp(-1, cmdlnopts);
}
}
#define HASHFNO (3)
#define HASHFNO (4)
static uint32_t my(const char *str){
char buf[MAXCMDLEN+1];
uint32_t hash = 0, *c = (uint32_t*)buf;
bzero(buf, sizeof(buf));
int len = strlen(str);
memcpy(buf, str, len);
len = (len + 3) / 4;
for(int i = 0; i < len; ++i)
hash = (hash << 2) + c[i];
return hash;
}
// djb2 & sdbm: http://www.cse.yorku.ca/~oz/hash.html
static uint32_t djb2(const char *str){
uint32_t hash = 5381;
uint32_t c;
while((c = (uint32_t)*str++))
hash = ((hash << 7) + hash) + c;
//hash = hash * 31 + c;
//hash = hash * 33 + c;
return hash;
}
static uint32_t sdbm(const char *str){
@@ -84,6 +95,17 @@ static uint32_t jenkins(const char *str){
}
static const char *hashsources[HASHFNO] = {
"static uint32_t hashf(const char *str){\n\
char buf[CMD_MAXLEN+1];\n\
uint32_t hash = 0, *c = (uint32_t*)buf;\n\
bzero(buf, sizeof(buf));\n\
int len = strlen(str);\n\
memcpy(buf, str, len);\n\
len = (len + 3) / 4;\n\
for(int i = 0; i < len; ++i)\n\
hash = (hash << 2) + c[i];\n\
return hash;\n\
}\n",
"static uint32_t hashf(const char *str){\n\
uint32_t hash = 5381;\n\
uint32_t c;\n\
@@ -112,13 +134,14 @@ static const char *hashsources[HASHFNO] = {
}\n"
};
static uint32_t (*hash[HASHFNO])(const char *str) = {djb2, sdbm, jenkins};
static const char *hashnames[HASHFNO] = {"DJB2", "SDBM", "Jenkins"};
static uint32_t (*hash[HASHFNO])(const char *str) = {my, djb2, sdbm, jenkins};
static const char *hashnames[HASHFNO] = {"My", "DJB2", "SDBM", "Jenkins"};
typedef struct{
char str[32]; // string command
char fname[32]; // function namee
uint32_t hash; // command hash
char str[MAXCMDLEN+1]; // string command define (capital letters)
char fname[MAXCMDLEN+1]; // function name
char macroname[MAXCMDLEN+1];// macro name
uint32_t hash; // command hash
} strhash;
static int sorthashesH(const void *a, const void *b){ // sort by hash
@@ -143,11 +166,11 @@ static FILE *openoutp(const char *name){
}
static char *macroname(const char *cmd){
static char macro[32];
static char macro[MAXCMDLEN+1];
int i = 0;
while(i < 31 && *cmd){
while(i < MAXCMDLEN && *cmd){
char c = *cmd++;
if(!isalnum(c)) c = '_';
if(!isalpha(c)) c = '_';
if(islower(c)) c = toupper(c);
macro[i++] = c;
}
@@ -156,9 +179,9 @@ static char *macroname(const char *cmd){
}
static char *fnname(const char *cmd){
static char fn[32];
static char fn[MAXCMDLEN+1];
int i = 0;
while(i < 31 && *cmd){
while(i < MAXCMDLEN && *cmd){
char c = *cmd++;
if(!isalpha(c)) c = '_';
if(isupper(c)) c = tolower(c);
@@ -170,17 +193,14 @@ static char *fnname(const char *cmd){
static const char *fhdr =
"int parsecmd(const char *str){\n\
char cmd[CMD_MAXLEN + 1];\n\
if(!str || !*str) return RET_CMDNOTFOUND;\n\
int i = 0;\n\
while(*str > '@' && i < CMD_MAXLEN){ cmd[i++] = *str++; }\n\
cmd[i] = 0;\n\
if(*str){\n\
while(*str <= ' ') ++str;\n\
}\n\
char *args = (char*) str;\n\
uint32_t h = hashf(cmd);\n\
switch(h){\n\n"
if(!str || !*str) return RET_CMDNOTFOUND;\n\
bzero(lastcmd, sizeof(lastcmd));\n\
int i = 0;\n\
while(*str > '@' && i < CMD_MAXLEN){ lastcmd[i++] = *str++; }\n\
while(*str && *str <= ' ') ++str;\n\
char *args = (char*) str;\n\
uint32_t h = hashf(lastcmd);\n\
switch(h){\n"
;
static const char *ffooter =
" default: break;\n\
@@ -189,43 +209,58 @@ static const char *ffooter =
}\n\n"
;
static const char *fns =
"int fn_%s(_U_ uint32_t hash, _U_ char *args) WAL; // \"%s\" (%u)\n\n"
"int fn_%s(uint32_t _U_ hash, char _U_ *args) WAL; // \"%s\" (%u)\n"
;
static const char *headercontent = "#ifndef _U_\n\
static const char *fnsh =
"int fn_%s(uint32_t, char*); // \"%s\" (%u)\n"
;
static const char *headercontent =
"// Generated by HASHGEN (https://github.com/eddyem/eddys_snippets/tree/master/stringHash4MCU_)\n\
// Licensed by GPLv3\n\
#pragma once\n\
#ifndef _U_\n\
#define _U_ __attribute__((__unused__))\n\
#endif\n\n\
#define CMD_MAXLEN (32)\n\n\
#define CMD_MAXLEN (%d)\n\n\
enum{\n\
RET_HELP = -3,\n\
RET_CMDNOTFOUND = -2,\n\
RET_WRONGCMD = -1,\n\
RET_BAD = 0,\n\
RET_GOOD = 1\n\
RET_GOOD = 0,\n\
RET_BAD = 1\n\
};\n\n\
int parsecmd(const char *cmdwargs);\n\n";
int parsecmd(const char *cmdwargs);\n\n\
extern char lastcmd[];\n\n";
static const char *sw =
" case CMD_%s:\n\
return fn_%s(h, args);\n\
break;\n";
static const char *srchdr =
"#include <stdint.h>\n\
"// Generated by HASHGEN (https://github.com/eddyem/eddys_snippets/tree/master/stringHash4MCU_)\n\
// Licensed by GPLv3\n\
#include <stdint.h>\n\
#include <stddef.h>\n\
#include <string.h>\n\
#include \"%s\"\n\n\
#ifndef WAL\n\
#define WAL __attribute__ ((weak, alias (\"__f1\")))\n\
#endif\n\nstatic int __f1(_U_ uint32_t h, _U_ char *a){return 1;}\n\n"
#endif\n\nstatic int __f1(uint32_t _U_ h, char _U_ *a){return RET_BAD;}\n\n\
char lastcmd[CMD_MAXLEN + 1];\n\n"
;
static void build(strhash *H, int hno, int hlen){
green("Generate files for hash function '%s'\n", hashnames[hno]);
int lmax = 1;
for(int i = 0; i < hlen; ++i){
strcpy(H[i].macroname, macroname(H[i].str));
int l = strlen(H[i].str);
if(l > lmax){
lmax = l;
}
}
lmax = (lmax + 3)/4;
lmax *= 4;
lmax *= 4; // round by 4 bytes
// resort H by strings
qsort(H, hlen, sizeof(strhash), sorthashesS);
FILE *source = openoutp(G.sourcefile), *header = openoutp(G.headerfile);
@@ -235,26 +270,36 @@ static void build(strhash *H, int hno, int hlen){
fprintf(source, fns, H[i].fname, H[i].str, H[i].hash);
}
}
fprintf(header, "%s", headercontent);
fprintf(source, "%s\n", hashsources[hno]);
fprintf(header, headercontent, lmax);
fprintf(source, "\n%s\n", hashsources[hno]);
fprintf(source, "%s", fhdr);
for(int i = 0; i < hlen; ++i){
char *m = macroname(H[i].str);
fprintf(source, sw, m, H[i].fname);
fprintf(header, "#define CMD_%-*s (%u)\n", lmax, m, H[i].hash);
fprintf(source, sw, H[i].macroname, H[i].fname);
fprintf(header, "#define CMD_%-*s (%u)\n", lmax, H[i].macroname, H[i].hash);
}
fprintf(source, "%s", ffooter);
fclose(source);
fprintf(header, "\n");
for(int i = 0; i < hlen; ++i){
fprintf(header, "#define STR_%-*s \"%s\"\n", lmax, H[i].macroname, H[i].str);
}
if(G.genfunc){
fprintf(header, "\n");
for(int i = 0; i < hlen; ++i){
fprintf(header, fnsh, H[i].fname, H[i].str, H[i].hash);
}
}
fclose(header);
}
int main(int argc, char **argv){
initial_setup();
sl_init();
parse_args(argc, argv);
if(!G.dict) ERRX("point dictionary file");
if(!G.headerfile) ERRX("point header source file");
if(!G.sourcefile) ERRX("point c source file");
mmapbuf *b = My_mmap(G.dict);
sl_mmapbuf_t *b = sl_mmap(G.dict);
if(!b) ERRX("Can't open %s", G.dict);
char *word = b->data;
strhash *H = MALLOC(strhash, ALLOCSZ);
@@ -267,19 +312,26 @@ int main(int argc, char **argv){
}
while(*word && *word < 33) ++word;
if(!*word) break;
char *nxt = strchr(word, '\n');
char *eol = strchr(word, '\n');
char *sp = strchr(word, ' ');
char *nxt = eol;
if(sp){ // got space after command - truncate
if(eol){
if(eol > sp) nxt = sp; // space before strend
}else nxt = sp; // no strend, but have space
};
if(nxt){
int len = nxt - word;
if(len > 31) len = 31;
if(len > MAXCMDLEN) len = MAXCMDLEN;
strncpy(H[idx].str, word, len);
H[idx].str[len] = 0;
}else{
snprintf(H[idx].str, 31, "%s", word);
snprintf(H[idx].str, MAXCMDLEN, "%s", word);
}
snprintf(H[idx].fname, 31, "%s", fnname(H[idx].str));
snprintf(H[idx].fname, MAXCMDLEN, "%s", fnname(H[idx].str));
++idx;
if(!nxt) break;
word = nxt + 1;
if(!eol) break;
word = eol + 1;
}
// test fname matches
qsort(H, idx, sizeof(strhash), sorthashesF);
@@ -300,7 +352,11 @@ int main(int argc, char **argv){
strhash *p = H;
int nmatches = 0;
for(int i = 0; i < imax1; ++i, ++p){ // test hash matches
if(p->hash == p[1].hash) ++nmatches;
if(p->hash == p[1].hash){
red("Found matched pair:");
printf(" '%s' and '%s'\n", p->str, p[1].str);
++nmatches;
}
}
if(nmatches == 0){
build(H, hno, idx);
@@ -310,6 +366,6 @@ int main(int argc, char **argv){
}
if(hno == HASHFNO) WARNX("Can't find proper hash function");
FREE(H);
My_munmap(b);
sl_munmap(b);
return 0;
}

View File

@@ -1,117 +0,0 @@
/*
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <string.h>
#include <usefull_macros.h>
#define ALLOCSZ (5000)
#define DJB2
#if defined DJB2
// djb2 http://www.cse.yorku.ca/~oz/hash.html
static uint32_t hash(const char *str){
uint32_t hash = 5381;
uint32_t c;
while((c = (uint32_t)*str++))
hash = ((hash << 5) + hash) + c;
//hash = hash * 31 + c;
//hash = hash * 33 + c;
return hash;
}
#elif defined SDBM
static uint32_t hash(const char *str){ // sdbm
uint32_t hash = 5381;
uint32_t c;
while((c = (uint32_t)*str++))
hash = c + (hash << 6) + (hash << 16) - hash;
return hash;
}
#elif defined JENKINS
uint32_t hash(const char *str){
uint32_t hash = 0, c;
while((c = (uint32_t)*str++)){
hash += c;
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
#endif
typedef struct{
char str[32];
uint32_t hash;
} strhash;
static int sorthashes(const void *a, const void *b){
register uint32_t h1 = ((strhash*)a)->hash, h2 = ((strhash*)b)->hash;
if(h2 > h1) return h2 - h1;
else return -((h1 - h2));
}
int main(int argc, char **argv){
//char buf[32];
initial_setup();
if(argc != 2) ERRX("Usage: %s dictionary_file", argv[0]);
mmapbuf *b = My_mmap(argv[1]);
if(!b) ERRX("Can't open %s", argv[1]);
char *word = b->data;
strhash *H = MALLOC(strhash, ALLOCSZ);
int l = ALLOCSZ, idx = 0;
while(*word){
if(idx >= l){
l += ALLOCSZ;
H = realloc(H, sizeof(strhash) * l);
if(!H) ERR("realloc()");
}
char *nxt = strchr(word, '\n');
if(nxt){
int len = nxt - word;
if(len > 31) len = 31;
strncpy(H[idx].str, word, len);
H[idx].str[len] = 0;
//strncpy(buf, word, len);
//buf[len] = 0;
}else{
//snprintf(buf, 31, "%s", word);
snprintf(H[idx].str, 31, "%s", word);
}
H[idx].hash = hash(H[idx].str);
//printf("word: %s\n", buf);
//printf("%u\t%s\n", hash(buf), buf);
//printf("%u\t%s\n", H[idx].hash, H[idx].str);
++idx;
if(!nxt) break;
word = nxt + 1;
}
qsort(H, idx, sizeof(strhash), sorthashes);
--idx;
strhash *p = H;
for(int i = 0; i < idx; ++i, ++p){
if(p->hash == p[1].hash){
printf("Words '%s' and '%s' have same hashes: %u\n", p->str, p[1].str, p->hash);
}
}
FREE(H);
My_munmap(b);
return 0;
}

View File

@@ -0,0 +1,61 @@
"absposN - GS absolute position (in steps, setter just changes current value)\n"
"accelN - GS accel/decel (steps/s^2)\n"
"adcN - G ADC value (N=0..3)\n"
"button[N] - G all or given (N=0..6) buttons' state\n"
"canerrcodes - G print last CAN errcodes\n"
"canfilter - GS can filters, format: bank# FIFO# mode(M/I) num0 [num1 [num2 [num3]]]\n"
"canflood - send/clear flood message: ID byte0 ... byteN\n"
"canfloodT - GS flood period (>=0ms)\n"
"canid - GS CAN ID of device\n"
"canignore - GS ignore list (max 10 IDs), negative to delete\n"
"canincrflood - send incremental flood message (ID is last for 'flood', stop by 'flood')\n"
"canpause - pause IN packets displaying\n"
"canreinit - reinit CAN\n"
"canresume - resume IN packets displaying\n"
"cansend - send data over CAN: send ID byte0 .. byteN (N<8)\n"
"canspeed - GS CAN speed (reinit if setter)\n"
"canstat - G CAN status\n"
"diagn[N] - G DIAG state of motor N (or all)\n"
"drvtypeN - GS driver type (0 - only step/dir, 1 - UART, 2 - SPI, 3 - reserved)\n"
"dumperr - dump error codes\n"
"dumpcmd - dump command codes\n"
"dumpconf - dump current configuration\n"
"dumpmotN - dump Nth motor configuration\n"
"dumpmotflags - dump motor flags' bits\n"
"dumpstates - dump motors' state codes\n"
"emstop[N] - emergency stop motor N or all\n"
"eraseflash [=N] - erase flash data storage (full or only N'th page of it)\n"
"esw[N] - G end-switches state\n"
"eswreactN - GS end-switches reaction (0 - ignore, 1 - ignore ESW1 and stop@0 only when moving negative, 2 - stop@any, 3 - stop@dir)\n"
"gotoN - GS move motor to given absolute position\n"
"gotozN - find zero position & refresh counters\n"
"gpioconfN* - GS GPIO configuration (0 - PUin, 1 - PPout, 2 - ODout), N=0..2\n"
"gpioN - GS GPIO values, N=0..2\n"
"help - print this help\n"
"maxspeedN - GS max speed (steps per sec)\n"
"maxstepsN - GS max steps (from zero ESW)\n"
"mcut - G MCU T\n"
"mcuvdd - G MCU Vdd\n"
"microstepsN - GS microsteps settings (2^0..2^9)\n"
"minspeedN - min speed (steps per sec)\n"
"motcurrentN - GS motor current (1..32 for 1/32..32/32 of max current)\n"
"motflagsN - motorN flags\n"
"motmul* - GS external multiplexer status (<0 - disable, 0..7 - enable and set address)\n"
"motno - GS motor number for next `pdn` commands\n"
"motreinit - re-init motors after configuration changed\n"
"pdnN - GS read/write TMC2209 registers over uart @ motor0\n"
"ping - echo given command back\n"
"relposN - GS relative move (get remaining)\n"
"relslowN - GS like 'relpos' but with slowest speed\n"
"reset - software reset\n"
"saveconf - save current configuration\n"
"screen* - GS screen enable (1) or disable (0)\n"
"speedlimit - G limiting speed for current microsteps setting\n"
"stateN - G motor state (0-relax, 1-accel, 2-move, 3-mvslow, 4-decel, 5-stall, 6-err)\n"
"stopN - stop motor with deceleration\n"
"time - G time from start (ms)\n"
"tmcbus* - GS TMC control bus (0 - USART, 1 - SPI)\n"
"udata* - GS data by usart in slave mode (text strings, '\\n'-terminated)\n"
"usartstatus* - GS status of USART1 (0 - off, 1 - master, 2 - slave)\n"
"vdrive - G approx voltage on Vdrive\n"
"vfive - G approx voltage on 5V bus\n"

4
stringHash4MCU_/mktestdic Executable file
View File

@@ -0,0 +1,4 @@
#!/bin/bash
awk '{print $1}' helpcmds.in |sed -e 's/"//' -e 's/\*//' -e 's/\[.*//' -e 's/N//' > testdic
./hashgen -d testdic -H hdr.h -S hdr.c -F

View File

@@ -3,8 +3,12 @@
gcc hashgen.c -o hashgen -lusefull_macros
./hashgen -d testdic -H hdr.h -S hdr.c -F
gcc hdr.c test.c strfunc.c -o test
./test "wrongarg"
./test "Wrong Arg"
./test "time 54 = some"
./test "voltage12 more"
./test "esw45 = some text"
./test "goto 55 = "
./test "stop 3256"
./test "mcut"

View File

@@ -7,12 +7,12 @@
static int noargs(uint32_t hash){
switch(hash){
case CMD_REBOOT: printf("REBOOT\n"); break;
case CMD_RESET: printf("REBOOT\n"); break;
case CMD_TIME: printf("TIME!\n"); break;
case CMD_TEMP: printf("Temp\n"); break;
default: printf("Unknown hash 0x%x\n", hash); return 0;
case CMD_MCUT: printf("Temp\n"); break;
default: printf("Unknown hash 0x%x\n", hash); return RET_BAD;
}
return 1;
return RET_GOOD;
}
static int withparno(uint32_t hash, char *args){
uint32_t N;
@@ -30,7 +30,7 @@ static int withparno(uint32_t hash, char *args){
switch(hash){
case CMD_ESW: fname = "ESW"; break;
case CMD_GOTO: fname = "GOTO"; break;
case CMD_POS: fname = "POS"; break;
case CMD_ABSPOS: fname = "ABSPOS"; break;
case CMD_STOP: fname = "STOP"; break;
default: fname = "unknown";
}
@@ -42,12 +42,12 @@ static int withparno(uint32_t hash, char *args){
// these functions should be global to substitute weak aliases
int fn_esw(uint32_t hash, char *args){return withparno(hash, args);}
int fn_goto(uint32_t hash, char *args){return withparno(hash, args);}
int fn_pos(uint32_t hash, char *args){return withparno(hash, args);}
int fn_abspos(uint32_t hash, char *args){return withparno(hash, args);}
int fn_stop(uint32_t hash, char *args){return withparno(hash, args);}
int fn_voltage(uint32_t hash, char *args){return withparno(hash, args);}
int fn_reboot(uint32_t hash, _U_ char *args){return noargs(hash);}
int fn_reset(uint32_t hash, _U_ char *args){return noargs(hash);}
int fn_time(uint32_t hash, _U_ char *args){return noargs(hash);}
int fn_temp(uint32_t hash, _U_ char *args){return noargs(hash);}
int fn_mcut(uint32_t hash, _U_ char *args){return noargs(hash);}
int main(int argc, char **argv){
if(argc != 2) return 1;

View File

@@ -1,8 +1,8 @@
pos
temp
voltage
time
reboot
stop
goto
abspos
esw
goto
stop
voltage
reset
time
mcut