]> rtime.felk.cvut.cz Git - lincan.git/blob - embedded/app/usbcan/main.c
6a5b3d4aa494dd2c1f818350979e9361c57dc17a
[lincan.git] / embedded / app / usbcan / main.c
1 /**************************************************************************/
2 /* File: main.c - setup and main loop of USB<->CAN converter              */
3 /*                                                                        */
4 /* LinCAN - (Not only) Linux CAN bus driver                               */
5 /* Copyright (C) 2002-2011 DCE FEE CTU Prague <http://dce.felk.cvut.cz>   */
6 /* Copyright (C) 2008 Jan Kriz email:johen@post.cz                        */
7 /*                                                                        */
8 /* LinCAN is free software; you can redistribute it and/or modify it      */
9 /* under terms of the GNU General Public License as published by the      */
10 /* Free Software Foundation; either version 2, or (at your option) any    */
11 /* later version.  LinCAN is distributed in the hope that it will be      */
12 /* useful, but WITHOUT ANY WARRANTY; without even the implied warranty    */
13 /* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU    */
14 /* General Public License for more details. You should have received a    */
15 /* copy of the GNU General Public License along with LinCAN; see file     */
16 /* COPYING. If not, write to the Free Software Foundation, 675 Mass Ave,  */
17 /* Cambridge, MA 02139, USA.                                              */
18 /*                                                                        */
19 /* To allow use of LinCAN in the compact embedded systems firmware        */
20 /* and RT-executives (RTEMS for example), main authors agree with next    */
21 /* special exception:                                                     */
22 /*                                                                        */
23 /* Including LinCAN header files in a file, instantiating LinCAN generics */
24 /* or templates, or linking other files with LinCAN objects to produce    */
25 /* an application image/executable, does not by itself cause the          */
26 /* resulting application image/executable to be covered by                */
27 /* the GNU General Public License.                                        */
28 /* This exception does not however invalidate any other reasons           */
29 /* why the executable file might be covered by the GNU Public License.    */
30 /* Publication of enhanced or derived LinCAN files is required although.  */
31 /**************************************************************************/
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <cpu_def.h>
36 #include <system_def.h>
37 #include <lt_timer.h>
38 #include <local_config.h>
39 #include <usb/usbdebug.h>
40 #include <usb/usb.h>
41 #include <usb/lpc.h>
42 #include <usb/usb_srq.h>
43 #include <mem_loc.h>
44 #include <keyval_id.h>
45 #include <hal_machperiph.h>
46 #include <keyval_loc.h>
47 #include <lpciap.h>
48 #include <lpciap_kvpb.h>
49
50 #include <endian.h>
51 #if __BYTE_ORDER == __BIG_ENDIAN
52   #include <byteswap.h>
53 #endif
54
55 #include "./can/can.h"
56 #include "./can/sja1000p.h"
57 #include "./can/main.h"
58
59 // #include "./can/can_sysdep.h"
60 #include "./can/modparms.h"
61 #include "./can/devcommon.h"
62
63 //#include "./can/ul_usb1.h"
64
65 #include "./can/setup.h"
66
67 #include "./usb/usb_defs.h"
68 #include "./usb/usb_vend.h"
69
70
71 #include "can/lpc17xx_can.h"
72
73 #define MASK_EP1RX  0x01
74 #define MASK_EP1TX  0x02
75
76 #define CAN_OP_MASK 0x80
77 #define CAN_OP_READ 0x80
78 #define CAN_OP_WRITE 0x00
79
80 #ifdef USB_MAX_PACKET
81         #undef USB_MAX_PACKET
82         #define USB_MAX_PACKET 16
83 #endif
84 /***********************************************************************
85  * Note:
86  * Comparing to LinCAN, there is no need to sleep for processes
87  * because the degree of filling of fifo from the client side
88  * is solved in main cycle (no new messages are accepted when full)
89  * and on the server side by speed of USB interface. FIFO in edge
90  * from SJA chip to USB interface should never be filled.
91  ***********************************************************************/
92
93 /***********************************************************************
94  * Note:
95  * Code is wittingly complex in order to ease future changes in hardware
96  * configuration and to make it as much similar as the code of LinCAN
97  ***********************************************************************/
98
99 LT_TIMER_DEC(lt_10msec)
100 LT_TIMER_IMP(lt_10msec)
101 LT_TIMER_DEC(lt_100msec)
102 LT_TIMER_IMP(lt_100msec)
103 LT_TIMER_DEC(lt_2sec)
104 LT_TIMER_IMP(lt_2sec)
105
106 typedef void (*FNC)(); //function ptr
107
108 /***********************************************************************
109  * global variables
110  ***********************************************************************/
111
112 usb_device_t usb_device;
113
114 usb_ep_t eps[NUM_ENDPOINTS];
115 unsigned char ep1_rx_buff[USB_MAX_PACKET];
116 unsigned char ep1_tx_buff[USB_MAX_PACKET];
117 uint8_t timer_str,timer_rx_off,timer_tx_off,timer_configured;
118 volatile uint8_t bootloader_run;
119
120 uint8_t vendor_ret;
121
122 int processlocal;
123
124 int baudrate[MAX_TOT_CHIPS];
125 struct canhardware_t canhardware;
126 struct canhardware_t *hardware_p=&canhardware;
127 struct canchip_t *chips_p[MAX_TOT_CHIPS];
128 struct msgobj_t *objects_p[MAX_TOT_MSGOBJS];
129
130 struct canuser_t *canuser;
131
132 extern int init_chip_struct(struct candevice_t *candev, int chipnr, int irq, long baudrate);
133 extern int register_chip_struct(struct canchip_t *chip, int minorbase);
134 extern int register_obj_struct(struct msgobj_t *obj, int minorbase);
135
136 /***********************************************************************
137  * IF SOMETHING BAD HAPPENED
138  ***********************************************************************/
139
140 int sys_err(){
141   
142   unsigned char i=0;
143
144   while(1) {
145     if (lt_100msec_expired(100)) {
146       i++;
147       if (i&1) {
148         SET_OUT_PIN(LED_PORT,LED_ERR);
149       } else {
150         CLR_OUT_PIN(LED_PORT,LED_ERR);
151       }
152      #ifdef WATCHDOG_ENABLED
153       watchdog_feed();
154      #endif /* WATCHDOG_ENABLED */
155     }
156   }
157 }
158
159 /***********************************************************************
160  * Microsecond delay routine
161  ***********************************************************************/
162 /*
163 void udelay(long time)
164 {
165   volatile long ticks=(time * CCLK) / 2000000;
166   do{
167     ticks--;
168   } while(ticks>0);
169 }
170 */
171
172 /***********************************************************************
173  * Routine for visible LED blinking (on USB transmission)
174  ***********************************************************************/
175
176 void timer_10ms(void)
177 {
178   if (timer_tx_off!=0) timer_tx_off--;
179   else SET_OUT_PIN(LED_PORT,LED1_BIT);
180   if (timer_rx_off!=0) timer_rx_off--;
181   else SET_OUT_PIN(LED_PORT,LED2_BIT);
182
183 /*  if (timer_configured!=0) timer_configured--;
184   else {
185     timer_configured=20;
186                 CLR_OUT_PIN(LED_PORT,LED1_BIT);
187                 CLR_OUT_PIN(LED_PORT,LED2_BIT);
188                 timer_rx_off=timer_tx_off=5;
189   }*/
190 }
191
192 /***********************************************************************
193  * Main routine
194  ***********************************************************************/
195
196 int main(void)
197 {
198         struct candevice_t *candev;
199         struct canchip_t *chip=NULL;
200         struct msgobj_t *obj;
201         struct canque_ends_t *qends;
202         struct canque_edge_t *edge,*qedge;
203         struct canque_slot_t *slot;
204         struct canmsg_t canmsg;
205         can_spin_irqflags_t iflags;
206
207         int chipnr,bd;
208         int i,size,m=0;
209
210         CANMSG("Starting USBCAN module firmware...\n");
211
212 //      volatile int i=0;
213         bootloader_run=0;
214         /***********************************/
215
216         lt_10msec_init();
217         lt_100msec_init();
218         lt_2sec_init();
219
220         // DEBUG
221         //SET_OUT_PIN(LED_PORT,LED_ERR);
222         //CLR_OUT_PIN(LED_PORT,LED_GP);
223
224         if (USB_MAX_PACKET<16){
225                 CANMSG("Maximum packet size less than 16B (is %dB)\n",USB_MAX_PACKET);
226                 sys_err();
227         }
228
229
230         //***********************************************************************
231         // * CAN device initialization - device side (adapted from LinCAN setup.c)
232         // ***********************************************************************
233
234 //      useless with lpc17xx (defined in can_lpcbusemu.c)
235 //      can_init();
236
237
238         DEBUGMSG("Initiating CAN device initialization\n");
239         baudrate[0]=1000;
240
241         canqueue_kern_initialize();
242
243         hardware_p->nr_boards=1;
244
245         candev=(struct candevice_t *)malloc(sizeof(struct candevice_t));
246         if (!candev){
247                 CANMSG("No space left in memory\n");
248                 sys_err();
249         }
250         memset(candev, 0, sizeof(struct candevice_t));
251
252         hardware_p->candevice[0]=candev;
253         candev->candev_idx=0;
254         candev->io_addr=0;
255         candev->dev_base_addr=0;
256
257         candev->hwspecops=(struct hwspecops_t *)malloc(sizeof(struct hwspecops_t));
258         if (!candev->hwspecops){
259                 CANMSG("No space left in memory\n");
260                 sys_err();
261         }
262         memset(candev->hwspecops, 0, sizeof(struct hwspecops_t));
263
264         
265
266         // DEBUG
267         //ul_usb1_register(candev->hwspecops);  //(defined in ul_usb1.c)
268         // register for another board:
269         can_lmc1_register(candev->hwspecops);
270
271         
272
273         bd=baudrate[0];
274         if (candev->hwspecops->init_hw_data(candev)){
275                 CANMSG("HW data could not be initialized\n");
276                 sys_err();
277         }
278
279         // Alocate and initialize the chip structures
280         for (chipnr=0; chipnr < candev->nr_all_chips; chipnr++) {
281 //              if(chipnr<irqnum)
282 //                      irqsig=irq[*irq_param_idx_p+chipnr];
283                 if (init_chip_struct(candev, chipnr, 0, bd*1000)){
284                         CANMSG("Chip structure could not be initialized\n");
285                         sys_err();
286                 }
287         }
288
289
290
291         for (chipnr=0; chipnr < candev->nr_all_chips; chipnr++) {
292                 struct canchip_t *chip=candev->chip[chipnr];
293                 int objnr;
294
295                 register_chip_struct(chip, m);
296
297                 for (objnr=0; objnr<chip->max_objects; objnr++) {
298                         register_obj_struct(chip->msgobj[objnr], m);
299                         if(m>=0) m++;
300                 }
301         }
302
303
304         if (candev->hwspecops->request_io(candev))
305                 sys_err();
306         candev->flags|=CANDEV_IO_RESERVED;
307
308
309         if (candev->hwspecops->reset(candev))
310                 sys_err();
311
312
313         for(chipnr=0; chipnr<candev->nr_all_chips; chipnr++) {
314                 if((chip=candev->chip[chipnr])==NULL)
315                         continue;
316
317                 if(chip->chipspecops->attach_to_chip(chip)<0) {
318 //                      CANMSG("Initial attach to the chip HW failed\n");
319                         sys_err();
320                 }
321
322                 chip->flags |= CHIP_ATTACHED;
323
324                 // used with lpc17xx:
325                 if(can_chip_setup_irq(chip)<0) {
326                         CANMSG("Error to setup chip IRQ\n");
327                         sys_err();
328                 }
329
330         }
331
332         if (candev->flags & CANDEV_PROGRAMMABLE_IRQ)
333                 if (candev->hwspecops->program_irq(candev)){
334 //                      CANMSG("Error to program board interrupt\n");
335                         sys_err();
336                 }
337
338         //***********************************************************************
339         // * CAN device initialization - client side (adapted from LinCAN open.c)
340         // ***********************************************************************
341
342
343         chip=candev->chip[0];
344         obj=chip->msgobj[0];
345         atomic_inc(&obj->obj_used);
346         can_msgobj_set_fl(obj,OPENED);
347
348         if (chip->flags & CHIP_CONFIGURED)
349                 DEBUGMSG("Device is already configured.\n");
350         else {
351                 if (chip->chipspecops->chip_config(chip))
352                         CANMSG("Error configuring chip.\n");
353                 else
354                         chip->flags |= CHIP_CONFIGURED;
355
356                 if (chip->chipspecops->pre_read_config(chip,obj)<0)
357                         CANMSG("Error initializing chip for receiving\n");
358
359         } // End of chip configuration
360
361
362         canuser = (struct canuser_t *)malloc(sizeof(struct canuser_t));
363         if(canuser == NULL) sys_err();
364         canuser->flags=0;
365 //      canuser->userinfo.fileinfo.file = file;
366         canuser->msgobj = obj;
367 //      canuser->magic = CAN_USER_MAGIC;
368 //      file->private_data = canuser;
369
370         qends = (struct canque_ends_t *)malloc(sizeof(struct canque_ends_t));
371         if(qends == NULL) sys_err();
372         canqueue_ends_init_kern(qends);
373         canuser->qends = qends;
374
375         //required to synchronize with RT-Linux context
376         can_spin_lock_irqsave(&canuser_manipulation_lock, iflags);
377         list_add(&canuser->peers, &obj->obj_users);
378         can_spin_unlock_irqrestore(&canuser_manipulation_lock, iflags);
379
380         if(canqueue_connect_edge(edge=canque_new_edge_kern(MAX_BUF_LENGTH),
381                 canuser->qends, obj->qends)<0) sys_err();
382
383         if(canqueue_connect_edge(canuser->rx_edge0=canque_new_edge_kern(MAX_BUF_LENGTH),
384                 obj->qends, canuser->qends)<0) sys_err();
385         //FIXME: more generic model should be used there
386         canque_edge_decref(canuser->rx_edge0);
387         canque_edge_decref(edge);
388
389
390
391         /***********************************************************************
392          * USB Init
393          ***********************************************************************/
394
395         memset( &usb_device, 0, sizeof( usb_device));
396         usb_device.id = 1;
397         usb_device.devdes_table = &usb_devdes_table;
398         usb_device.init = usb_lpc_init;
399         usb_debug_set_level(DEBUG_LEVEL_NONE);
400         usb_device.cntep = NUM_ENDPOINTS;
401         usb_device.ep = eps;
402
403         eps[0].max_packet_size = USB_MAX_PACKET;
404         eps[1].max_packet_size = USB_MAX_PACKET;
405         eps[0].epnum = 0x01;
406         eps[1].epnum = 0x81;
407         eps[0].event_mask = 0x04;
408         eps[1].event_mask = 0x08;
409         eps[0].udev = &usb_device;
410         eps[1].udev = &usb_device;
411
412         usb_device.vendor_fnc=usbcan_vendor;
413
414         usb_init(&usb_device);
415         usb_connect(&usb_device);
416         usb_device.ep_events |= MASK_EP1TX;
417
418         /***********************************************************************
419          * Start
420          ***********************************************************************/
421
422         timer_rx_off=timer_tx_off=timer_str=timer_configured=0;
423
424
425         printf("Main loop\n");
426
427         while (1) {
428
429                 usb_check_events(&usb_device);
430                 usb_control_response(&usb_device);
431
432 // useless with lpc17xx:
433 //              if (!(IO0PIN&P0_SJA1000_INT_PIN)) //INT PIN is inverted
434 //                      chip->chipspecops->irq_handler(0,chip);
435
436                 if (usb_device.ep_events & MASK_EP1RX) {  //EP1RX - data waiting to receive
437                         
438                         if (canque_get_inslot(qends, &qedge, &slot, 0)>=0){ //Free slot obtained
439
440                                 size=usb_udev_read_endpoint(&eps[0],ep1_rx_buff,16);
441                                 if (size==16){
442                                         uint16_t msgflags;
443                                         uint32_t msgid;
444                                         canmsg.cob=0;
445                                         canmsg.length=*(uint8_t *)(ep1_rx_buff+1);
446                                         if (canmsg.length > CAN_MSG_LENGTH)
447                                                 canmsg.length=CAN_MSG_LENGTH;
448                                         msgflags=*(uint16_t *)(ep1_rx_buff+2);
449                                         msgid=*(uint32_t *)(ep1_rx_buff+4);
450                                         #if __BYTE_ORDER == __BIG_ENDIAN
451                                                 msgflags  = bswap_16( msgflags);
452                                                 msgid  = bswap_32( msgid);
453                                         #endif
454                                         canmsg.flags=msgflags;
455                                         canmsg.id=msgid;
456
457                                         for (i=0;i<canmsg.length;i++){
458                                                 canmsg.data[i]=*(unsigned char*)(ep1_rx_buff+8+i);
459                                         }
460                                         for (;i<CAN_MSG_LENGTH;i++){
461                                                 canmsg.data[i]=0;
462                                         }
463                                         /* Automatic selection of extended format if ID>2047 */
464                                         if (canmsg.id & ~0x7ffl & MSG_ID_MASK ) canmsg.flags |= MSG_EXT;
465                                         /* has been dependent on "extended" option */
466                         
467                                         slot->msg=canmsg;
468                                         canque_put_inslot(qends, qedge, slot);
469
470                                 }
471                                 else
472                                         canque_abort_inslot(qends,qedge,slot);
473                                         
474
475                                 timer_rx_off=50;        //rosviceni diody pri prijmu
476                                 CLR_OUT_PIN(LED_PORT,LED2_BIT);
477                                 usb_device.ep_events &= ~MASK_EP1RX;
478                         
479                                         
480                         }
481                         
482
483 /*                      if (size==2){
484                                 uint8_t val;
485                                 if ((data[0]&CAN_OP_MASK)==CAN_OP_READ){ // Get data from CAN device and return to caller
486                                         val = can_read(data[0] & ~CAN_OP_MASK);
487                                         *(data+1)=val;
488                                         usb_udev_write_endpoint(&eps[1],(unsigned char *)data,size);
489                                         timer_rx_off=50;        //rosviceni diody pri prijmu
490                                         CLR_OUT_PIN(LED_PORT,LED2_BIT);
491                                         usb_can_send=0;
492                                 }
493                                 if ((data[0]&CAN_OP_MASK)==CAN_OP_WRITE){ // Save data to CAN device
494                                         can_write(data[1], data[0] & ~CAN_OP_MASK);
495                                         timer_tx_off=50;                //rozsviceni diod pri vysilani
496                                         CLR_OUT_PIN(LED_PORT,LED1_BIT);
497                                 }
498                         }*/
499                 }
500
501                 
502                 if(usb_device.ep_events & MASK_EP1TX){ //EP1TX - data transmitted
503                         if(canque_test_outslot(qends, &qedge, &slot)>=0){
504                                 DEBUGMSG("CAN message ready to send over usb\n");
505                                 uint16_t msgflags;
506                                 uint32_t msgid;
507
508                                 *(uint8_t *)(ep1_tx_buff)=0;
509                                 *(uint8_t *)(ep1_tx_buff+1)=slot->msg.length;
510
511                                 msgflags=slot->msg.flags;
512                                 msgid=slot->msg.id;
513                                 #if __BYTE_ORDER == __BIG_ENDIAN
514                                         msgflags  = bswap_16( msgflags);
515                                         msgid  = bswap_32( msgid);
516                                 #endif
517
518                                 *(uint16_t *)(ep1_tx_buff+2)=msgflags;
519                                 *(uint32_t *)(ep1_tx_buff+4)=msgid;
520                                 for (i=0;i<slot->msg.length;i++){
521                                         *(uint8_t *)(ep1_tx_buff+8+i)=slot->msg.data[i];
522                                 }
523                                 for (;i<CAN_MSG_LENGTH;i++){
524                                         *(uint8_t *)(ep1_tx_buff+8+i)=0;
525                                 }
526                                 usb_udev_write_endpoint(&eps[1],ep1_tx_buff,16);
527
528                                 canque_free_outslot(qends, qedge, slot);
529                                 timer_tx_off=50;                //rozsviceni diod pri vysilani
530                                 CLR_OUT_PIN(LED_PORT,LED1_BIT);
531                                 usb_device.ep_events &= ~MASK_EP1TX;
532
533                         }
534                         
535
536                 }
537                 
538
539                 //if (usb_can_send && )
540
541 #ifdef WATCHDOG_ENABLED
542                 watchdog_feed();
543 #endif /* WATCHDOG_ENABLED */
544
545                 /* 10ms timer */
546                 if (lt_10msec_expired(10))
547                         timer_10ms();
548         }
549
550         SET_OUT_PIN(LED_PORT,LED_GP);
551         SET_OUT_PIN(LED_PORT,LED_ERR);
552
553         /* unreachable code */
554 #ifdef SDCC
555         vec_jmp(0x0);  /* need to call a function from misc to correct linking */
556 #endif
557         return 0;
558 }