Update tutorial docs and flash writing/reading
[fw/stlink] / flash / main.c
1 /* simple wrapper around the stlink_flash_write function */
2
3 // TODO - this should be done as just a simple flag to the st-util command line...
4
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/types.h>
10 #include "stlink-common.h"
11
12
13 struct opts
14 {
15   unsigned int do_read;
16   const char* devname;
17   const char* filename;
18   stm32_addr_t addr;
19   size_t size;
20 };
21
22 static void usage(void)
23 {
24     puts("stlinkv1 command line: ./flash {read|write} /dev/sgX path addr <size>");
25     puts("stlinkv2 command line: ./flash {read|write} path addr <size>");
26 }
27
28 static int get_opts(struct opts* o, int ac, char** av)
29 {
30   /* stlinkv1 command line: ./flash {read|write} /dev/sgX path addr <size> */
31   /* stlinkv2 command line: ./flash {read|write} path addr <size> */
32
33   unsigned int i = 0;
34
35   if (ac < 3) return -1;
36
37   /* stlinkv2 */
38   o->devname = NULL;
39
40   if (strcmp(av[0], "read") == 0)
41   {
42     o->do_read = 1;
43
44     /* stlinkv1 mode */
45     if (ac == 5)
46     {
47       o->devname = av[1];
48       i = 1;
49     }
50
51     o->size = strtoul(av[i + 3], NULL, 10);
52   }
53   else if (strcmp(av[0], "write") == 0)
54   {
55     o->do_read = 0;
56
57     /* stlinkv1 mode */
58     if (ac == 4)
59     {
60       o->devname = av[1];
61       i = 1;
62     }
63   }
64   else
65   {
66     return -1;
67   }
68
69   o->filename = av[i + 1];
70   o->addr = strtoul(av[i + 2], NULL, 16);
71
72   return 0;
73
74
75
76 int main(int ac, char** av)
77 {
78   stlink_t* sl = NULL;
79   struct opts o;
80   int err = -1;
81
82   if (get_opts(&o, ac - 1, av + 1) == -1)
83   {
84     printf("invalid command line\n");
85     usage();
86     goto on_error;
87   }
88
89   if (o.devname != NULL) /* stlinkv1 */
90   {
91     sl = stlink_v1_open(100);
92     if (sl == NULL) goto on_error;
93   }
94   else /* stlinkv2 */
95   {
96     sl = stlink_open_usb(100);
97     if (sl == NULL) goto on_error;
98   }
99
100   if (stlink_current_mode(sl) == STLINK_DEV_DFU_MODE)
101     stlink_exit_dfu_mode(sl);
102
103   if (stlink_current_mode(sl) != STLINK_DEV_DEBUG_MODE)
104     stlink_enter_swd_mode(sl);
105
106   stlink_reset(sl);
107
108   if (o.do_read == 0) /* write */
109   {
110     err = stlink_fwrite_flash(sl, o.filename, o.addr);
111     if (err == -1)
112     {
113       printf("stlink_fwrite_flash() == -1\n");
114       goto on_error;
115     }
116   }
117   else /* read */
118   {
119     err = stlink_fread(sl, o.filename, o.addr, o.size);
120     if (err == -1)
121     {
122       printf("stlink_fread() == -1\n");
123       goto on_error;
124     }
125   }
126
127   /* success */
128   err = 0;
129
130  on_error:
131   if (sl != NULL) stlink_close(sl);
132
133   return err;
134 }