text
stringlengths 65
6.05M
| lang
stringclasses 8
values | type
stringclasses 2
values | id
stringlengths 64
64
|
---|---|---|---|
#include <linux/build-salt.h>
#include <linux/module.h>
#include <linux/vermagic.h>
#include <linux/compiler.h>
BUILD_SALT;
MODULE_INFO(vermagic, VERMAGIC_STRING);
MODULE_INFO(name, KBUILD_MODNAME);
__visible struct module __this_module
__section(.gnu.linkonce.this_module) = {
.name = KBUILD_MODNAME,
.init = init_module,
#ifdef CONFIG_MODULE_UNLOAD
.exit = cleanup_module,
#endif
.arch = MODULE_ARCH_INIT,
};
MODULE_INFO(intree, "Y");
#ifdef CONFIG_RETPOLINE
MODULE_INFO(retpoline, "Y");
#endif
static const struct modversion_info ____versions[]
__used __section(__versions) = {
{ 0x7459220b, "module_layout" },
{ 0x722a53d5, "param_ops_ushort" },
{ 0x84972054, "param_ops_byte" },
{ 0xaad49c42, "param_array_ops" },
{ 0xcae09d, "usbatm_usb_disconnect" },
{ 0x5c85af9b, "usb_deregister" },
{ 0x9ce89892, "usb_register_driver" },
{ 0xc5850110, "printk" },
{ 0x890b3d61, "_dev_err" },
{ 0x6ca935a7, "usb_set_interface" },
{ 0xeee83d72, "usb_driver_claim_interface" },
{ 0xa6c77a72, "usb_altnum_to_altsetting" },
{ 0x5569741e, "__dynamic_dev_dbg" },
{ 0xce42315c, "usb_driver_release_interface" },
{ 0x837b7b09, "__dynamic_pr_debug" },
{ 0x79aa04a2, "get_random_bytes" },
{ 0xc8aedd9, "usbatm_usb_probe" },
{ 0xbdfb6dbb, "__fentry__" },
};
MODULE_INFO(depends, "usbatm");
MODULE_INFO(srcversion, "8874015DD65844BE4130A67");
| C | CL | c1dd05a75549e7f49de7bdd6e0d6cb813cc2281e18aa8b6493c7612d658bdb87 |
#include "Common.h"
#include <time.h>
#include <sys/types.h>
#include <sys/timeb.h>
int printTime(char *ampm)
{
char buff[128];//, ampm[] = "AM";
__time64_t lgtime;
struct __timeb64 timstruct;
struct tm *today, *thegmt, xmas = { 0, 0, 12, 25, 11, 90 };
/* set time zone from TZ environment variable. If TZ is not set,
* the operating system is queried to obtain the default value
* for the variable.*/
_tzset();
/* get UNIX-style time and display as number and string. */
_time64(&lgtime);
printf("Time in seconds since UTC 1/1/70:\t%ld seconds\n", lgtime);
printf("UNIX time and date:\t\t\t%s", _ctime64(&lgtime));
/* display UTC. */
thegmt = _gmtime64(&lgtime);
printf("Coordinated universal time, UTC:\t%s", asctime(thegmt));
/* display operating system-style date and time. */
_strtime(buff);
printf("OS time:\t\t\t\t%s\n", buff);
_strdate(buff);
printf("OS date:\t\t\t\t%s\n", buff);
/* convert to time structure and adjust for PM if necessary. */
today = _localtime64(&lgtime);
if (today->tm_hour >= 12) {
strcpy(ampm, "PM");
today->tm_hour -= 12;
}
/* adjust if midnight hour. */
if (today->tm_hour == 0)
today->tm_hour = 12;
/* pointer addition is used to skip the first 11
* characters and printf() is used to trim off terminating
* characters.*/
printf("12-hour time:\t\t\t\t%.8s %s\n", asctime(today) + 11, ampm);
/* print additional time information. */
_ftime64(&timstruct);
printf("Plus milliseconds:\t\t\t%u\n", timstruct.millitm);
printf("Zone difference in hours from UTC:\t%u hours\n",
timstruct.timezone / 60);
printf("Time zone name:\t\t\t\t%s\n", _tzname[0]);
printf("Daylight savings:\t\t\t%s\n",
timstruct.dstflag ? "YES" : "NOT SET");
/* make time for noon on Christmas, 1990. */
if (_mktime64(&xmas) != (__time64_t ) -1)
printf("Christmas\t\t\t\t%s", asctime(&xmas));
/* use time structure to build a customized time string. */
today = _localtime64(&lgtime);
/* use strftime to build a customized time string. */
strftime(buff, 128, "Today is %A, day %d of %B in the year %Y.\n", today);
printf(buff);
return 0;
}
| C | CL | dbb045c8c28ffd1048d26f4cd938add73cb11e7c7c38ade81f574f24aca03d90 |
#include "malloc_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
// TODO Do not use printf/dprintf for errors printing
/*
* This file handles pages allocation and freeing.
*
* The process asks the kernel for pages using `mmap`
* and frees them using `munmap`.
*
* The size of a memory page is retrieved using `sysconf(_SC_PAGE_SIZE)`.
*/
/*
* Returns the size in bytes of a page of memory on the current system.
*/
size_t _get_page_size(void)
{
static size_t page_size = 0;
if(likely(page_size == 0))
{
page_size = sysconf(_SC_PAGE_SIZE);
#ifdef _MALLOC_DEBUG
dprintf(STDERR_FILENO, "malloc: page size: %zu bytes\n", page_size);
#endif
}
if(unlikely(page_size == 0))
{
dprintf(STDERR_FILENO, "abort: _SC_PAGE_SIZE == 0\n");
abort();
}
return page_size;
}
/*
* Asks the kernel for `n` pages and returns the pointer to the beginning
* of the allocated region of memory.
*/
__attribute__((malloc))
void *_alloc_pages(const size_t n)
{
return mmap(NULL, n * _get_page_size(),
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
}
/*
* Frees the given region of `n` memory pages starting at `addr`.
*/
void _free_pages(void *addr, const size_t n)
{
munmap(addr, n * _get_page_size());
}
| C | CL | e3f577ce20c24a1ab168eeb2c973f48040162fc9c17a27b269147b364b8ad472 |
/*
* this file will handle the ipc message queue operations
* author <[email protected]>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <drv_ipc_msgque.h>
#include <ipc-common.h>
static IPC_MSQINFO *g_msqinfo = NULL;
static DEFINE_SPINLOCK(lock);
static UINT32 ipc_calcNeddBuffSize(void)
{
UINT32 buffsize;
buffsize = (sizeof(IPC_SEND_MSG) * 2) * IPC_SENDTO_MAX;
return buffsize;
}
// implement init function
INT32 ipc_msgque_init(void)
{
UINT32 i;
int ret;
UINT32 tmpbuff;
IPC_MSGQUE *p_msgque;
if(g_msqinfo)
{
printk(KERN_INFO "ipc message queue inited already\n");
return -1;
}
g_msqinfo = (IPC_MSQINFO *)kmalloc(sizeof(IPC_MSQINFO), GFP_KERNEL);
if(!g_msqinfo)
{
printk(KERN_ERR "unable allocate memory for IPC_MSQINFO \n");
return -ENOMEM;
}
// this is consistent memory
g_msqinfo->syscmdbuf_vir = dma_alloc_coherent(NULL, ipc_calcNeddBuffSize(), (dma_addr_t *)&(g_msqinfo->syscmdbuf_dma), GFP_KERNEL);
if(unlikely(!(g_msqinfo->syscmdbuf_vir)))
{
printk(KERN_ERR "unable to allocate mem for syscmdbuf_vir\n");
ret = -ENOMEM;
goto __ERR1;
}
tmpbuff = (UINT32)g_msqinfo->syscmdbuf_vir;
for (i = 0; i< IPC_MSG_QUEUE_NUM ; i++)
{
p_msgque = &(g_msqinfo->msgQueTbl[i]);
p_msgque->initkey = 0;
// reset token string
g_msqinfo->msgQueTokenStr[i][0] = 0;
}
for(i = 0; i < IPC_SENDTO_MAX; i++)
{
sema_init(&(g_msqinfo->sndmsg_buffTbl[i].semid), 1); // init semaphore like mutex
g_msqinfo->sndmsg_buffTbl[i].pingponidx = 0;
g_msqinfo->sndmsg_buffTbl[i].sndmsg[0] = (IPC_SEND_MSG*)tmpbuff;
tmpbuff += sizeof(IPC_SEND_MSG);
g_msqinfo->sndmsg_buffTbl[i].sndmsg[1] = (IPC_SEND_MSG*)tmpbuff;
tmpbuff += sizeof(IPC_SEND_MSG);
}
if(tmpbuff - g_msqinfo->syscmdbuf_vir != ipc_calcNeddBuffSize())
{
printk(KERN_ERR "error calc buff\n");
ret = -EFAULT;
goto __ERR2;
}
return 0;
__ERR2:
dma_free_coherent(NULL, ipc_calcNeddBuffSize(), g_msqinfo->syscmdbuf_vir, (dma_addr_t)g_msqinfo->syscmdbuf_dma);
__ERR1:
kfree(g_msqinfo);
g_msqinfo = NULL;
return ret;
}
void ipc_msgque_exit(void)
{
UINT32 i;
IPC_MSGQUE *p_msgque;
if(unlikely(!g_msqinfo))
{
printk(KERN_ERR "g_msqinfo is null\n");
return;
}
for(i = 0; i < IPC_MSG_QUEUE_NUM; i++)
{
p_msgque = &(g_msqinfo->msgQueTbl[i]);
p_msgque->initkey = 0;
}
dma_free_coherent(NULL, ipc_calcNeddBuffSize(), g_msqinfo->syscmdbuf_vir, (dma_addr_t)g_msqinfo->syscmdbuf_dma);
kfree(g_msqinfo);
g_msqinfo = NULL;
}
// @input : name -> pname
// @output: key -> hash
// @return: 0 if error otherwise success
static UINT16 ipc_msgque_namehash(const char *pname)
{
UINT16 hash = 0;
//TODO:
const char *pchar = pname;
if(!pname)
{
printk(KERN_ERR "pname is null");
return 0;
}
// refer to open source
while((*pchar) != 0)
{
hash = ((hash&1) ? 0x8000 : 0) + (hash>>1) + (*pchar);
pchar++;
}
printk(KERN_INFO "name = %s key = %d",pname, hash);
return hash;
}
UINT16 ipc_msgque_ftok(unsigned long coreid, const char *path)
{
unsigned long flags;
int i;
char *queuetoken = NULL;
if(unlikely(!g_msqinfo))
{
printk(KERN_ERR "ipc msq not init\n");
return -1;
}
spin_lock_irqsave(&lock, flags);
for(i = 0; i < IPC_MSG_QUEUE_NUM; i++)
{
queuetoken = g_msqinfo->msgQueTokenStr[i];
if(queuetoken[0] == 0)
{
strncpy(queuetoken, path, IPC_MSG_QUEUE_TOKEN_STR_MAXLEN);
printk(KERN_INFO "tokenstr[%d] = %s\n", i, queuetoken);
break;
}
}
spin_unlock_irqrestore(&lock, flags);
return ipc_msgque_namehash(path);
}
// input : key
// output: msqid
INT32 ipc_msgque_get(unsigned long coreid, INT32 key)
{
int i = 0;
IPC_MSGQUE *p_msgque;
unsigned long flags;
if(unlikely(!g_msqinfo))
{
printk(KERN_ERR "ipc msgque not init yet\n");
return -1;
}
spin_lock_irqsave(&lock, flags);
for(i = 0 ; i < IPC_MSG_QUEUE_NUM ; i++)
{
p_msgque = &(g_msqinfo->msgQueTbl[i]);
if((p_msgque->initkey == CFG_IPC_INIT_KEY) && (key == p_msgque->sharekey))
{
spin_unlock_irqrestore(&lock, flags);
printk(KERN_ERR "generate key 0x%04x is duplicate\r\n",key);
return -1;
}
}
if(i = 0 ; i < IPC_MSG_QUEUE_NUM; i++)
{
p_msgque = &(g_msqinfo->msgQueTbl[i]);
if(p_msgque->initkey != CFG_IPC_INIT_KEY)
break;
}
if(unlikely(i>=IPC_MSG_QUEUE_NUM))
{
spin_unlock_irqrestore(&lock, flags);
printk(KERN_ERR "all of queue are used\n");
return -2;
}
p_msgque->initkey = CFG_IPC_INIT_KEY;
p_msgque->msqid = i;
p_msgque->sharekey = key;
p_msgque->indx = IPC_MSG_ELEMENT_NUM - 1;
p_msgque->outdx = 0;
p_msgque->count = 0;
spin_unlock_irqrestore(&lock, flags);
printk(KERN_INFO "msqid = %d, sharekey = 0x%4x\n",p_msgque->msqid, p_msgque->sharekey);
return p_msgque->msqid;
}
// get msq id by key
// input -> key
// output -> queid
INT32 ipc_msgque_getIDbyKey(unsigned long coreid, INT32 key)
{
UINT32 i;
IPC_MSGQUE *pmsgque = NULL;
if(unlikely(!g_msqinfo))
{
return -1;
}
for(i=0; i<IPC_MSG_QUEUE_NUM; i++)
{
pmsgque = &(g_msqinfo->msgQueTbl[i]);
if(!pmsgque)
{
return -2
}
if(pmsgque->initkey == CFG_IPC_INIT_KEY && (UINT32)key == pmsgque->sharekey)
{
return pmsgque->msqid;
}
}
return -3;
}
// implement function get queue by id
IPC_MSGQUE *ipc_msgque_getQuebyID(unsigned long coreid, UINT32 msqid)
{
int i = 0;
IPC_MSGQUE *p_msgque = NULL;
if(unlikely(!g_msqinfo))
{
printk(KERN_ERR "msg queue not init yet\n");
return NULL;
}
if(msqid >= IPC_MSG_QUEUE_NUM)
{
printk(KERN_ERR "msqid invalid\n");
return NULL;
}
//for(i = 0; i < IPC_MSG_QUEUE_NUM; i++)
//{
// p_msgque = &(g_msqinfo->msgQueTbl[i]);
// if(p_msgque->msqid == msqid)
// break;
//}
p_msgque = &(g_msqinfo->msgQueTbl[msqid]);
if(p_msgque->initkey != CFG_IPC_INIT_KEY)
{
printk("msqid %d is not initial\n",msqid);
return NULL;
}
return p_msgque;
}
// implement function get token by key
char *ipc_msgque_getTokenByKey(unsigned long coreid, UINT32 key)
{
int i = 0;
if(unlikely(!g_msqinfo))
{
printk("msg not initial yet\n");
return NULL;
}
for(i = 0; i < IPC_MSG_QUEUE_NUM; i++)
{
if(ipc_msgque_namehash(g_msqinfo->msgQueTokenStr[i]) == key)
{
return g_msqinfo->msgQueTokenStr[i];
}
}
return NULL;
}
INT32 ipc_msgque_rel(unsigned long coreid, UINT32 msqid)
{
IPC_MSGQUE *p_msgque =NULL;
unsigned long flags;
char *token = NULL;
spin_lock_irqsave(&lock, flags);
p_msgque = ipc_msgque_getQuebyID(coreid, msqid);
if(unlikely(!p_msgque))
{
spin_unlock_irqrestore(&lock, flags);
printk(KERN_ERR "uable get queue bu ID\n");
return -1;
}
token = ipc_msgque_getTokenByKey(coreid, p_msgque->sharekey);
if(token)
{
printk(KERN_INFO "release token %s\n",token);
token[0]=0;
}
else
{
printk(KERN_ERR "unable to get token by key\n");
return -2;
}
p_msgque->initkey = 0;
spin_unlock_irqrestore(&lock, flags);
return 0;
}
bool ipc_msgque_isempty(IPC_MSGQUE *msgque)
{
if(!msgque)
{
printk(KERN_ERR "msgque is null\n");
return true;
}
if(msgque->indx == msgque->outdx)
{
return true;
}
else
{
return false;
}
}
static UINT32 ipc_msgque_getElementCount(IPC_MSGQUE *msgque)
{
if(!msgque)
{
return -1;
}
else
{
return msgque->count;
}
}
bool ipc_msgque_isfull(IPC_MSGQUE *msgque)
{
UINT32 count;
if(!msgque)
{
printk(KERN_ERR "msgque is null\n");
return true;
}
count = ipc_msgque_getElementCount(msgque);
if(count >= IPC_MSG_ELEMENT_NUM)
{
return true;
}
else
{
return false;
}
}
bool ipc_msgque_isvalid(IPC_MSGQUE *pmsgque, UINT32 sharekey)
{
if(!pmsgque)
{
printk(KERN_ERR "msgque is null\n");
return false;
}
if(likely(pmsgque->initkey == CFG_IPC_INIT_KEY && sharekey = pmsgque->sharekey))
{
return true;
}
else
{
return false;
}
}
INT32 ipc_msgque_enqueue(IPC_MSGQUE *msgque, IPC_MSG *msg)
{
IPC_MSG *Tmpmsgque = NULL;
unsigned long flags;
INT32 ret = 0;
spin_lock_irqsave(&long, flags);
if(ipc_msgque_isfull(msgque))
{
return -1;
}
msgque->indx = ((msgque->indx + 1) % IPC_MSG_ELEMENT_NUM);
Tmpmsgque = &(msgque->element[msgque->indx]);
if(Tmpmsgque)
{
Tmpmsgque->size = msg->size;
memcpy(Tmpmsgque->data, msg->data, msg->size);
msgque->count++;
}
else
{
ret = -2;
}
spin_unlock_irqrestore(&long, flags);
return ret;
}
/*
* will called as soon as data is coming to get data which store in register then push it into queue
*
*/
INT32 ipc_msgque_msgpost(unsigned long coreid, UINT32 msqid, void *pmsgaddr, UINT32 msgsize)
{
IPC_MSGQUE *pmsgque = NULL;
IPC_MSG rcvmsg;
INT32 ret;
unsigned long flags;
printk(KERN_DEBUG "msqid = %d msg addr = 0x%08x msg size = %d",msqid, noncache_addr, cmd.data_size);
if(unlikely(!pmsgaddr))
{
printk(KERN_ERR "msgaddr is null\n");
return -1;
}
if(msgsize > IPC_MSG_ELEMENT_SIZE)
{
printk(KERN_ERR "msgsize is over limit\n");
return -2;
}
spin_lock_irqsave(&lock, flags);
pmsgque = ipc_msgque_getQuebyID(coreid, msqid);
if(unlikely(!pmsgque))
{
printk(KERN_ERR "ipc_msgque_getQuebyID failed\n");
spin_unlock_irqrestore(&lock, flags);
return -3;
}
memcpy(&rcvmsg.data, pmsgaddr, msgsize);
rcvmsg.size = msgsize;
ret = ipc_msgque_enqueue(pmsgque, &rcvmsg);
if(unlikely(ret != 0))
{
spin_unlock_irqrestore(&lock, flags);
return -4;
}
spin_unlock_irqrestore(&lock, flags);
return ret;
}
INT32 ipc_msgque_dequeue(IPC_MSGQUE *msgque, IPC_MSG *msg)
{
IPC_MSG *Tmpmsgque = NULL;
unsigned long flags;
spin_lock_irqsave(&lock, flags);
if(ipc_msgque_isempty(msgque))
{
return -1;
}
Tmpmsgque = &(msgque->element[msgque->outdx]);
if(Tmpmsgque)
{
msg->size= Tmpmsgque->size;
msgque->outdx = (msgque->outdx+1) % IPC_MSG_ELEMENT_NUM;
memcpy(msg->data, Tmpmsgque->data, Tmpmsgque->size);
msgque->count--;
}
else
{
ret = -2;
}
spin_unlock_irqrestore(&long, flags);
return 0;
}
IPC_SEND_MSG* ipc_msgque_lockSndMsgBuff(unsigned long coreid, IPC_SENTO sendTo)
{
IPC_SNDMSG_BUFF *psndmsgbuf = NULL;
if(unlikely(!g_msqinfo))
{
printk(KERN_ERR "g_msqinfo is null\n");
return NULL;
}
psndmsgbuf = g_msqinfo->sndmsg_buffTbl[sendTo - 1];
if(unlikely(!psndmsgbuf))
{
printk(KERN_ERR "psndmsgbuf is null\n");
return NULL;
}
down_interruptible(&psndmsgbuf.semid);
if(psndmsgbuf.pingponidx == 0)
{
psndmsgbuf.pingponidx = 1;
return psndmsgbuf.sndmsg[0];
}
else
{
psndmsgbuf.pingponidx = 0
return psndmsgbuf.sndmsg[1];
}
}
void ipc_msgque_unlockSndMsgBuff(unsigned long coreid, IPC_SENTO sendTo)
{
IPC_SNDMSG_BUFF *psndmsgbuf = NULL;
if(unlikely(!g_msqinfo))
{
printk(KERN_ERR "g_msqinfo is null\n");
return;
}
psndmsgbuf = g_msqinfo->sndmsg_buffTbl[sendTo -1];
up(&psndmsgbuf.semid);
}
UINT32 ipc_msgque_getPhyAddr(UINT32 virt_addr)
{
if(unlikely(!g_msqinfo))
{
printk(KERN_ERR "g_msqinfo is null\n");
return virt_addr;
}
else
{
// (g_msqinfo->syscmdbuf_vir - g_msqinfo->syscmdbuf_dma)
// size bw virtual addr and physical address
return virt_addr - (g_msqinfo->syscmdbuf_vir - g_msqinfo->syscmdbuf_dma);
}
}
| C | CL | b0b4d3af3c77f8030974f65e30291866572587f61e9eca95c1c4feb285a7522b |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef scalar_t__ u32 ;
struct fsg_lun {scalar_t__ num_sectors; scalar_t__ blkbits; unsigned int sense_data_info; int info_valid; void* sense_data; int /*<<< orphan*/ blksize; int /*<<< orphan*/ filp; scalar_t__ file_length; } ;
struct fsg_common {int* cmnd; struct fsg_buffhd* next_buffhd_to_fill; struct fsg_lun* curlun; } ;
struct fsg_buffhd {int /*<<< orphan*/ buf; } ;
typedef unsigned int ssize_t ;
typedef unsigned int loff_t ;
/* Variables and functions */
int EINTR ;
int EINVAL ;
int EIO ;
scalar_t__ FSG_BUFLEN ;
int /*<<< orphan*/ LDBG (struct fsg_lun*,char*,int,...) ;
void* SS_INVALID_FIELD_IN_CDB ;
void* SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE ;
void* SS_UNRECOVERED_READ_ERROR ;
int /*<<< orphan*/ VLDBG (struct fsg_lun*,char*,unsigned int,unsigned long long,int) ;
int /*<<< orphan*/ current ;
int /*<<< orphan*/ fsg_lun_fsync_sub (struct fsg_lun*) ;
scalar_t__ get_unaligned_be16 (int*) ;
scalar_t__ get_unaligned_be32 (int*) ;
int /*<<< orphan*/ invalidate_sub (struct fsg_lun*) ;
unsigned int kernel_read (int /*<<< orphan*/ ,int /*<<< orphan*/ ,unsigned int,unsigned int*) ;
unsigned int min (unsigned int,scalar_t__) ;
unsigned int round_down (unsigned int,int /*<<< orphan*/ ) ;
scalar_t__ signal_pending (int /*<<< orphan*/ ) ;
scalar_t__ unlikely (int) ;
__attribute__((used)) static int do_verify(struct fsg_common *common)
{
struct fsg_lun *curlun = common->curlun;
u32 lba;
u32 verification_length;
struct fsg_buffhd *bh = common->next_buffhd_to_fill;
loff_t file_offset, file_offset_tmp;
u32 amount_left;
unsigned int amount;
ssize_t nread;
/*
* Get the starting Logical Block Address and check that it's
* not too big.
*/
lba = get_unaligned_be32(&common->cmnd[2]);
if (lba >= curlun->num_sectors) {
curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
return -EINVAL;
}
/*
* We allow DPO (Disable Page Out = don't save data in the
* cache) but we don't implement it.
*/
if (common->cmnd[1] & ~0x10) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
verification_length = get_unaligned_be16(&common->cmnd[7]);
if (unlikely(verification_length == 0))
return -EIO; /* No default reply */
/* Prepare to carry out the file verify */
amount_left = verification_length << curlun->blkbits;
file_offset = ((loff_t) lba) << curlun->blkbits;
/* Write out all the dirty buffers before invalidating them */
fsg_lun_fsync_sub(curlun);
if (signal_pending(current))
return -EINTR;
invalidate_sub(curlun);
if (signal_pending(current))
return -EINTR;
/* Just try to read the requested blocks */
while (amount_left > 0) {
/*
* Figure out how much we need to read:
* Try to read the remaining amount, but not more than
* the buffer size.
* And don't try to read past the end of the file.
*/
amount = min(amount_left, FSG_BUFLEN);
amount = min((loff_t)amount,
curlun->file_length - file_offset);
if (amount == 0) {
curlun->sense_data =
SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
curlun->sense_data_info =
file_offset >> curlun->blkbits;
curlun->info_valid = 1;
break;
}
/* Perform the read */
file_offset_tmp = file_offset;
nread = kernel_read(curlun->filp, bh->buf, amount,
&file_offset_tmp);
VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
(unsigned long long) file_offset,
(int) nread);
if (signal_pending(current))
return -EINTR;
if (nread < 0) {
LDBG(curlun, "error in file verify: %d\n", (int)nread);
nread = 0;
} else if (nread < amount) {
LDBG(curlun, "partial file verify: %d/%u\n",
(int)nread, amount);
nread = round_down(nread, curlun->blksize);
}
if (nread == 0) {
curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
curlun->sense_data_info =
file_offset >> curlun->blkbits;
curlun->info_valid = 1;
break;
}
file_offset += nread;
amount_left -= nread;
}
return 0;
} | C | CL | f0a34c2e5896f4342b1f12a9b4126456d3059534f880af604203c0ae36476f07 |
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/nvram/import/nvram-format.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <skiboot.h>
#include <nvram.h>
static struct chrp_nvram_hdr *skiboot_part_hdr;
static uint8_t chrp_nv_cksum(struct chrp_nvram_hdr *hdr)
{
struct chrp_nvram_hdr h_copy = *hdr;
uint8_t b_data, i_sum, c_sum;
uint8_t *p = (uint8_t *)&h_copy;
unsigned int nbytes = sizeof(h_copy);
h_copy.cksum = 0;
for (c_sum = 0; nbytes; nbytes--) {
b_data = *(p++);
i_sum = c_sum + b_data;
if (i_sum < c_sum)
i_sum++;
c_sum = i_sum;
}
return c_sum;
}
#define NVRAM_SIG_FW_PRIV 0x51
#define NVRAM_SIG_SYSTEM 0x70
#define NVRAM_SIG_FREE 0x7f
#define NVRAM_NAME_COMMON "common"
#define NVRAM_NAME_FW_PRIV "ibm,skiboot"
#define NVRAM_NAME_FREE "wwwwwwwwwwww"
#define NVRAM_SIZE_COMMON 0x10000
#define NVRAM_SIZE_FW_PRIV 0x1000
int nvram_format(void *nvram_image, uint32_t nvram_size)
{
struct chrp_nvram_hdr *h;
unsigned int offset = 0;
prerror("NVRAM: Re-initializing (size: 0x%08x)\n", nvram_size);
memset(nvram_image, 0, nvram_size);
/* Create private partition */
if (nvram_size - offset < NVRAM_SIZE_FW_PRIV)
return -1;
h =
#ifdef __HOSTBOOT_MODULE
reinterpret_cast<chrp_nvram_hdr*>(
static_cast<uint8_t*>(nvram_image) + offset);
#else
nvram_image + offset;
#endif
h->sig = NVRAM_SIG_FW_PRIV;
h->len = cpu_to_be16(NVRAM_SIZE_FW_PRIV >> 4);
strcpy(h->name, NVRAM_NAME_FW_PRIV);
h->cksum = chrp_nv_cksum(h);
prlog(PR_DEBUG, "NVRAM: Created '%s' partition at 0x%08x"
" for size 0x%08x with cksum 0x%02x\n",
NVRAM_NAME_FW_PRIV, offset,
be16_to_cpu(h->len), h->cksum);
offset += NVRAM_SIZE_FW_PRIV;
/* Create common partition */
if (nvram_size - offset < NVRAM_SIZE_COMMON)
return -1;
h =
#ifdef __HOSTBOOT_MODULE
reinterpret_cast<chrp_nvram_hdr*>(
static_cast<uint8_t*>(nvram_image) + offset);
#else
nvram_image + offset;
#endif
h->sig = NVRAM_SIG_SYSTEM;
h->len = cpu_to_be16(NVRAM_SIZE_COMMON >> 4);
strcpy(h->name, NVRAM_NAME_COMMON);
h->cksum = chrp_nv_cksum(h);
prlog(PR_DEBUG, "NVRAM: Created '%s' partition at 0x%08x"
" for size 0x%08x with cksum 0x%02x\n",
NVRAM_NAME_COMMON, offset,
be16_to_cpu(h->len), h->cksum);
offset += NVRAM_SIZE_COMMON;
/* Create free space partition */
if (nvram_size - offset < sizeof(struct chrp_nvram_hdr))
return -1;
h =
#ifdef __HOSTBOOT_MODULE
reinterpret_cast<chrp_nvram_hdr*>(
static_cast<uint8_t*>(nvram_image) + offset);
#else
nvram_image + offset;
#endif
h->sig = NVRAM_SIG_FREE;
h->len = cpu_to_be16((nvram_size - offset) >> 4);
/* We have the full 12 bytes here */
memcpy(h->name, NVRAM_NAME_FREE, 12);
h->cksum = chrp_nv_cksum(h);
prlog(PR_DEBUG, "NVRAM: Created '%s' partition at 0x%08x"
" for size 0x%08x with cksum 0x%02x\n",
NVRAM_NAME_FREE, offset, be16_to_cpu(h->len), h->cksum);
return 0;
}
static const char *find_next_key(const char *start, const char *end)
{
/*
* Unused parts of the partition are set to NUL. If we hit two
* NULs in a row then we assume that we have hit the end of the
* partition.
*/
if (*start == 0)
return NULL;
while (start < end) {
if (*start == 0)
return start + 1;
start++;
}
return NULL;
}
/*
* Check that the nvram partition layout is sane and that it
* contains our required partitions. If not, we re-format the
* lot of it
*/
int nvram_check(void *nvram_image, const uint32_t nvram_size)
{
unsigned int offset = 0;
bool found_common = false;
skiboot_part_hdr = NULL;
while (offset + sizeof(struct chrp_nvram_hdr) < nvram_size) {
#ifdef __HOSTBOOT_MODULE
struct chrp_nvram_hdr *h = reinterpret_cast<chrp_nvram_hdr*>(
reinterpret_cast<uint8_t*>(nvram_image)
+ offset);
#else
struct chrp_nvram_hdr *h = nvram_image + offset;
#endif
if (chrp_nv_cksum(h) != h->cksum) {
prerror("NVRAM: Partition at offset 0x%x"
" has bad checksum: 0x%02x vs 0x%02x\n",
offset, h->cksum, chrp_nv_cksum(h));
goto failed;
}
if (be16_to_cpu(h->len) < 1) {
prerror("NVRAM: Partition at offset 0x%x"
" has incorrect 0 length\n", offset);
goto failed;
}
if (h->sig == NVRAM_SIG_SYSTEM &&
strcmp(h->name, NVRAM_NAME_COMMON) == 0)
found_common = true;
if (h->sig == NVRAM_SIG_FW_PRIV &&
strcmp(h->name, NVRAM_NAME_FW_PRIV) == 0)
skiboot_part_hdr = h;
offset += be16_to_cpu(h->len) << 4;
if (offset > nvram_size) {
prerror("NVRAM: Partition at offset 0x%x"
" extends beyond end of nvram !\n", offset);
goto failed;
}
}
if (!found_common) {
prlog_once(PR_ERR, "NVRAM: Common partition not found !\n");
goto failed;
}
if (!skiboot_part_hdr) {
prlog_once(PR_ERR, "NVRAM: Skiboot private partition not found !\n");
goto failed;
} else {
/*
* The OF NVRAM format requires config strings to be NUL
* terminated and unused memory to be set to zero. Well behaved
* software should ensure this is done for us, but we should
* always check.
*/
const char *last_byte = (const char *) skiboot_part_hdr +
be16_to_cpu(skiboot_part_hdr->len) * 16 - 1;
if (*last_byte != 0) {
prerror("NVRAM: Skiboot private partition is not NUL terminated");
goto failed;
}
}
prlog(PR_INFO, "NVRAM: Layout appears sane\n");
assert(skiboot_part_hdr);
return 0;
failed:
return -1;
}
/*
* nvram_query() - Searches skiboot NVRAM partition for a key=value pair.
*
* Returns a pointer to a NUL terminated string that contains the value
* associated with the given key.
*/
const char *nvram_query(const char *key)
{
const char *part_end, *start;
int key_len = strlen(key);
assert(key);
if (!nvram_has_loaded()) {
prlog(PR_DEBUG,
"NVRAM: Query for '%s' must wait for NVRAM to load\n",
key);
if (!nvram_wait_for_load()) {
prlog(PR_CRIT, "NVRAM: Failed to load\n");
return NULL;
}
}
/*
* The running OS can modify the NVRAM as it pleases so we need to be
* a little paranoid and check that it's ok before we try parse it.
*
* NB: nvram_validate() can update skiboot_part_hdr
*/
if (!nvram_validate())
return NULL;
assert(skiboot_part_hdr);
part_end = (const char *) skiboot_part_hdr
+ be16_to_cpu(skiboot_part_hdr->len) * 16 - 1;
start = (const char *) skiboot_part_hdr
+ sizeof(*skiboot_part_hdr);
if (!key_len) {
prlog(PR_WARNING, "NVRAM: search key is empty!\n");
return NULL;
}
if (key_len > 32)
prlog(PR_WARNING, "NVRAM: search key '%s' is longer than 32 chars\n", key);
while (start) {
int remaining = part_end - start;
prlog(PR_TRACE, "NVRAM: '%s' (%lu)\n",
start, strlen(start));
if (key_len + 1 > remaining)
return NULL;
if (!strncmp(key, start, key_len) && start[key_len] == '=') {
const char *value = &start[key_len + 1];
prlog(PR_DEBUG, "NVRAM: Searched for '%s' found '%s'\n",
key, value);
return value;
}
start = find_next_key(start, part_end);
}
prlog(PR_DEBUG, "NVRAM: '%s' not found\n", key);
return NULL;
}
| C | CL | 4aa0ed0aa6b69dc4116f87c87fae9985d374e4315abba6734218663af342030e |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
struct TYPE_2__ {int adh_reset; int /*<<< orphan*/ adh_directory; int /*<<< orphan*/ adh_trail_offset; int /*<<< orphan*/ adh_trail_name; int /*<<< orphan*/ * adh_remote; } ;
/* Variables and functions */
TYPE_1__* adhost ;
int /*<<< orphan*/ adist_remote_cond ;
int /*<<< orphan*/ adist_remote_mtx ;
int /*<<< orphan*/ adist_trail ;
int /*<<< orphan*/ cv_wait (int /*<<< orphan*/ *,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ mtx_lock (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ mtx_unlock (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ pjdlog_debug (int,char*,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ trail_close (int /*<<< orphan*/ ) ;
int trail_filefd (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ trail_filename (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ trail_next (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ trail_reset (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ trail_start (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ wait_for_dir () ;
int /*<<< orphan*/ wait_for_file_init (int) ;
__attribute__((used)) static bool
read_thread_wait(void)
{
bool newfile = false;
mtx_lock(&adist_remote_mtx);
if (adhost->adh_reset) {
reset:
adhost->adh_reset = false;
if (trail_filefd(adist_trail) != -1)
trail_close(adist_trail);
trail_reset(adist_trail);
while (adhost->adh_remote == NULL)
cv_wait(&adist_remote_cond, &adist_remote_mtx);
trail_start(adist_trail, adhost->adh_trail_name,
adhost->adh_trail_offset);
newfile = true;
}
mtx_unlock(&adist_remote_mtx);
while (trail_filefd(adist_trail) == -1) {
newfile = true;
wait_for_dir();
/*
* We may have been disconnected and reconnected in the
* meantime, check if reset is set.
*/
mtx_lock(&adist_remote_mtx);
if (adhost->adh_reset)
goto reset;
mtx_unlock(&adist_remote_mtx);
if (trail_filefd(adist_trail) == -1)
trail_next(adist_trail);
}
if (newfile) {
pjdlog_debug(1, "Trail file \"%s/%s\" opened.",
adhost->adh_directory,
trail_filename(adist_trail));
(void)wait_for_file_init(trail_filefd(adist_trail));
}
return (newfile);
} | C | CL | 5aefd9b587c08fdbf3219ff5228921473c6c77556391b94b673eb6434761127b |
#include <assert.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include "context.h"
#include "preempt.h"
#include "queue.h"
#include "uthread.h"
#define MAXTID 65535
enum State{
RUNNING,
READY,
BLOCKED,
EXITED
};
typedef struct tcb{
uthread_t tid;
enum State state;
uthread_ctx_t ctx;
void *top_of_stack;
uthread_func_t func;//function to execute
void *arg;//arguments of function
int retval;
uthread_t joinfrom_tid;
}tcb,*tcb_t;
queue_t uthread_lib;
tcb_t current_thread;
static int is_tid(void *data, void *arg);
int uthread_lib_init(void);
void uthread_destroy(tcb_t tcb);
static int printid(void *data, void *arg);
void print_all();
int uthread_lib_init(void)
{
if(uthread_lib!=NULL) return 0;
uthread_lib = queue_create();
//create the mainthread
tcb_t temp = (tcb_t)malloc(sizeof(tcb));
//memory allocation failure
if(!temp) return -1;
temp->tid=0;
temp->state = RUNNING;
current_thread = temp;
preempt_start(); // start preemption
return 0;
}
static int is_tid(void *data, void *arg) // checks if the TIDs match for a temp thread and the current thread
{
tcb_t tcb = (tcb_t)data;
uthread_t tid= *(uthread_t*)arg;
if(tcb->tid == tid) return 1;
else return 0;
}
static int printid(void *data, void *arg) // print function used to help debug
{
tcb_t tcb = (tcb_t)data;
printf("%d and state is %d",(int)(tcb->tid),tcb->state);
return 0;
}
void print_all() // print function used to help debug
{
printf("\n");
queue_iterate(uthread_lib,printid,NULL,NULL);
printf("\n");
}
tcb_t find_next_ready(){
// function is used to find the next thread that is READY
// and returns it to the yield function in order to
// switch to the proper context
tcb_t tcb;
int flag;
int count =0;
int len = queue_length(uthread_lib);
flag = queue_dequeue(uthread_lib,(void **)&tcb);
while(flag ==0 && tcb->state!=READY && count<len)
{
queue_enqueue(uthread_lib,(void *)tcb);
flag = queue_dequeue(uthread_lib,(void **)&tcb);
count ++;
}
return tcb;
}
void uthread_destroy(tcb_t tcb)
{
// frees the thread table
uthread_ctx_destroy_stack(tcb->top_of_stack);
free(tcb);
}
void uthread_yield(void)
{
preempt_enable(); // start preemption
preempt_disable();
if(current_thread->state!=EXITED)
{
// puts current thread at end of queue since we are switching to the next ready thread
queue_enqueue(uthread_lib,(void *)current_thread);
}
tcb_t next_ready = find_next_ready(); // finds the next ready thread
if(next_ready==NULL||next_ready->tid==current_thread->tid)
{
preempt_enable();
return;// no other thread ready
}
tcb_t prev = current_thread;
if(prev->state!=BLOCKED && prev->state!=EXITED) prev->state=READY;
next_ready->state = RUNNING; // sets new current thread to running
current_thread=next_ready;
uthread_ctx_switch(&(prev->ctx), &(next_ready->ctx)); // switches context registers
preempt_enable(); // enables preemption again
}
uthread_t uthread_self(void)
{
// returns the tid of a thread
preempt_enable();
return current_thread->tid;
}
int uthread_create(uthread_func_t func, void *arg)
{
// this function creates a new thread and puts it in the queue
if(!uthread_lib) uthread_lib_init();
preempt_enable();
preempt_disable();
tcb_t temp = (tcb_t)malloc(sizeof(tcb)); // creats temp thread
if(!temp)
{
preempt_enable();
return-1; //memory allocation failure
}
if(queue_length(uthread_lib)+1>MAXTID)
{
preempt_enable();
return-1;// tid overflow
}
// assigns appropriate info to the tcb
temp->tid=(unsigned short)(queue_length(uthread_lib)+1);
temp->joinfrom_tid=temp->tid; //initialized as an impossible value
temp->state = READY;
temp->top_of_stack = uthread_ctx_alloc_stack();
if(!(temp->top_of_stack))
{
preempt_enable();
return-1;//memory allocation failure
}
temp->func=func;
temp->arg=arg;
if(uthread_ctx_init(&(temp->ctx), temp->top_of_stack,temp->func,temp->arg)==-1)
{
preempt_enable();
return-1;//context creation failure
}
queue_enqueue(uthread_lib,(void*)temp); // places new thread into queue
preempt_enable();
return temp->tid;
}
void uthread_exit(int retval)
{
preempt_enable();
preempt_disable();
current_thread->retval = retval;
current_thread->state = EXITED; // current thread is set to EXITED
if(current_thread->joinfrom_tid!=current_thread->tid)
{ // means that this was joined from somewhere
tcb_t joinfrom;
queue_iterate(uthread_lib,is_tid,(void*)(¤t_thread->joinfrom_tid),(void**)&joinfrom);
joinfrom->state =READY; // unblock T2 and schedule T2 after all the currently runnable threads
queue_delete(uthread_lib,(void*)joinfrom);
queue_enqueue(uthread_lib,(void*)joinfrom);
}
queue_delete(uthread_lib,(void*)current_thread); // removes current thread
uthread_yield(); // goes to yeild to change to the next thread
preempt_enable();
}
int uthread_join(uthread_t tid, int *retval)
{
preempt_enable();
preempt_disable();
if(tid==0)
{
preempt_enable();
return -1;// the 'main' thread cannot be joined
}
if(current_thread->tid==tid)
{
preempt_enable();
return -1;// tid is the TID of the calling thread
}
tcb_t rst;
queue_iterate(uthread_lib,is_tid,(void*)(&tid),(void**)&rst);
if(rst==NULL)
{
preempt_enable();
return -1;// thread @tid cannot be found
}
else if(rst->joinfrom_tid!=rst->tid)
{
preempt_enable();
return -1;// thread @tid is already being joined
}
else if(rst->state==READY)
{ // T2 is still an active thread, T1 must be blocked
rst->joinfrom_tid=current_thread->tid;
current_thread->state=BLOCKED;
uthread_yield();
}
// when T2 is unblocked, it should come back here
if(rst->state==EXITED)
{ // T2 is already dead, T1 can collect T2 right away
if(retval!=NULL) *retval = rst->retval;
uthread_destroy(rst);
}
preempt_enable();
return 0;
}
| C | CL | 27868f04fab096469a2c0554cef9c04a9c5840830090a986f2157ce91cc2a80c |
/* Copyright (C) 1991 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The GNU C 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with the GNU C Library; see the file COPYING.LIB. If
not, write to the Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA. */
#ifndef _FNMATCH_H
#define _FNMATCH_H 1
/* Bits set in the FLAGS argument to `SIMPatternMatch'. */
#define FNM_PATHNAME (1 << 0)/* No wildcard can ever match `/'. */
#define FNM_NOESCAPE (1 << 1)/* Backslashes don't quote special chars. */
#define FNM_PERIOD (1 << 2)/* Leading `.' is matched only explicitly. */
#define __FNM_FLAGS (FNM_PATHNAME|FNM_NOESCAPE|FNM_PERIOD)
/* Value returned by `SIMPatternMatch' if STRING does not match PATTERN. */
#define FNM_NOMATCH 1
/* Match STRING against the filename pattern PATTERN,
returning zero if it matches, FNM_NOMATCH if not. */
extern int SIMPatternMatch();
#endif /* SIMPatternMatch.h */ | C | CL | 8b537aa20148e4750a1a1b61e9394d1cb924536b7f9960c8c5212101e4c82306 |
#ifndef GUI_STATE_H_
#define GUI_STATE_H_
#include <SDL.h>
// General flag for marking an error in one of the GUI states.
extern int isError;
// All the state IDs.
typedef enum {
MAIN_MENU,
CAT_CHOOSE,
CAT_CHOOSE_SKILL,
MOUSE_CHOOSE,
MOUSE_CHOOSE_SKILL,
GAME_PLAY,
LOAD_GAME,
GAME_EDITOR,
EDIT_GAME,
SAVE_GAME,
ERROR,
QUIT
} StateId;
// The GUI structure.
typedef struct GUI {
// The unique state id:
StateId stateId;
// The model and viewState. Assumed to be NULL until GUI is started and once it is stopped.
// The model and view state should NOT hold references to each other.
void *model, *viewState;
// The function pointer for starting this GUI - initializing the model and viewState as well as drawing the initial state of the GUI.
void (*start) (struct GUI* gui, void* initData);
// The function pointer for translating the SDL_Event to a logical event according to the current viewState.
// The logical event will be passed to the presenter which will take care of updating the model and/or the view.
// The data type of the logical event is assumed to be know by the presenter and will also be freed by it, if need be.
void* (*viewTranslateEvent) (void* viewState, SDL_Event* event);
// The function pointer for handling the given logical event.
// may or may not update the model and/or viewState.
// Returns the next state to transition to.
StateId (*presenterHandleEvent) (void* model, void* viewState, void* logicalEvent);
// The function pointer for deactivating this GUI - freeing the model and viewState and any other resources used.
// Returns the initialization data for the next state (can be NULL if not required).
void* (*stop) (struct GUI* gui, StateId nextStateId);
} GUIState;
#endif /* GUI_STATE_H_ */
| C | CL | 7f6dbff8e90e88152f6f23140b5a9dddcadd02577c87d9aba91c6f6f2545fb2c |
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N M M %
% P P NN N MM MM %
% PPPP N N N M M M %
% P N NN M M %
% P N N M M %
% %
% %
% Read/Write ImageMagick Image Format. %
% %
% %
% Software Design %
% John Cristy %
% July 1992 %
% %
% %
% Copyright (C) 2000 ImageMagick Studio, a non-profit organization dedicated %
% to making software imaging solutions freely available. %
% %
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick is furnished to do so, subject to the following conditions: %
% %
% The above copyright notice and this permission notice shall be included in %
% all copies or substantial portions of ImageMagick. %
% %
% The software is provided "as is", without warranty of any kind, express or %
% implied, including but not limited to the warranties of merchantability, %
% fitness for a particular purpose and noninfringement. In no event shall %
% ImageMagick Studio be liable for any claim, damages or other liability, %
% whether in an action of contract, tort or otherwise, arising from, out of %
% or in connection with ImageMagick or the use or other dealings in %
% ImageMagick. %
% %
% Except as contained in this notice, the name of the ImageMagick Studio %
% shall not be used in advertising or otherwise to promote the sale, use or %
% other dealings in ImageMagick without prior written authorization from the %
% ImageMagick Studio. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick.h"
#include "defines.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method IsPNM returns True if the image format type, identified by the
% magick string, is PNM.
%
% The format of the ReadPNMImage method is:
%
% unsigned int IsPNM(const unsigned char *magick,
% const unsigned int length)
%
% A description of each parameter follows:
%
% o status: Method IsPNM returns True if the image format type is PNM.
%
% o magick: This string is generally the first few bytes of an image file
% or blob.
%
% o length: Specifies the length of the magick string.
%
%
*/
Export unsigned int IsPNM(const unsigned char *magick,const unsigned int length)
{
if (length < 2)
return(False);
if ((*magick == 'P') && isdigit((int) magick[1]))
return(True);
return(False);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method ReadPNMImage reads a Portable Anymap image file and returns it.
% It allocates the memory necessary for the new Image structure and returns
% a pointer to the new image.
%
% The format of the ReadPNMImage method is:
%
% Image *ReadPNMImage(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image: Method ReadPNMImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or
% if the image cannot be read.
%
% o image_info: Specifies a pointer to an ImageInfo structure.
%
%
*/
static unsigned int PNMInteger(Image *image,const unsigned int base)
{
#define P7Comment "END_OF_COMMENTS"
int
c;
unsigned int
value;
/*
Skip any leading whitespace.
*/
do
{
c=ReadByte(image);
if (c == EOF)
return(0);
if (c == '#')
{
register char
*p,
*q;
unsigned int
length,
offset;
/*
Read comment.
*/
if (image->comments != (char *) NULL)
{
p=image->comments+Extent(image->comments);
length=p-image->comments;
}
else
{
length=MaxTextExtent;
image->comments=(char *)
AllocateMemory((length+strlen(P7Comment)+1)*sizeof(char));
p=image->comments;
}
offset=p-image->comments;
if (image->comments != (char *) NULL)
for ( ; (c != EOF) && (c != '\n'); p++)
{
if ((p-image->comments) >= length)
{
length<<=1;
length+=MaxTextExtent;
image->comments=(char *) ReallocateMemory((char *)
image->comments,(length+strlen(P7Comment)+1)*sizeof(char));
if (image->comments == (char *) NULL)
break;
p=image->comments+Extent(image->comments);
}
c=ReadByte(image);
*p=(char) c;
*(p+1)='\0';
}
if (image->comments == (char *) NULL)
{
MagickWarning(ResourceLimitWarning,"Memory allocation failed",
(char *) NULL);
return(0);
}
q=image->comments+offset;
if (Latin1Compare(q,P7Comment) == 0)
*q='\0';
continue;
}
} while (!isdigit(c));
if (base == 2)
return(c-'0');
/*
Evaluate number.
*/
value=0;
do
{
value*=10;
value+=c-'0';
c=ReadByte(image);
if (c == EOF)
return(0);
}
while (isdigit(c));
return(value);
}
Export Image *ReadPNMImage(const ImageInfo *image_info)
{
char
format;
Image
*image;
IndexPacket
index;
int
blue,
green,
red,
y;
MonitorHandler
handler;
Quantum
*scale;
register int
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned char
*pixels;
unsigned int
max_value,
packets,
status;
/*
Allocate image structure.
*/
image=AllocateImage(image_info);
if (image == (Image *) NULL)
return((Image *) NULL);
/*
Open image file.
*/
status=OpenBlob(image_info,image,ReadBinaryType);
if (status == False)
ReaderExit(FileOpenWarning,"Unable to open file",image);
/*
Read PNM image.
*/
status=ReadBlob(image,1,(char *) &format);
do
{
/*
Verify PNM identifier.
*/
if ((status == False) || (format != 'P'))
ReaderExit(CorruptImageWarning,"Not a PNM image file",image);
/*
Initialize image structure.
*/
format=ReadByte(image);
if (format == '7')
(void) PNMInteger(image,10);
image->columns=PNMInteger(image,10);
image->rows=PNMInteger(image,10);
if ((format == '1') || (format == '4'))
max_value=1; /* bitmap */
else
max_value=PNMInteger(image,10);
image->depth=max_value < 256 ? 8 : QuantumDepth;
if ((format != '3') && (format != '6'))
{
image->class=PseudoClass;
image->colors=max_value+1;
}
if (image_info->ping)
{
CloseBlob(image);
return(image);
}
if ((image->columns*image->rows) == 0)
ReaderExit(CorruptImageWarning,
"Unable to read image: image dimensions are zero",image);
scale=(Quantum *) NULL;
if (image->class == PseudoClass)
{
/*
Create colormap.
*/
image->colormap=(PixelPacket *)
AllocateMemory(image->colors*sizeof(PixelPacket));
if (image->colormap == (PixelPacket *) NULL)
ReaderExit(ResourceLimitWarning,"Memory allocation failed",image);
if (format != '7')
for (i=0; i < (int) image->colors; i++)
{
image->colormap[i].red=
((unsigned long) (MaxRGB*i)/(image->colors-1));
image->colormap[i].green=
((unsigned long) (MaxRGB*i)/(image->colors-1));
image->colormap[i].blue=
((unsigned long) (MaxRGB*i)/(image->colors-1));
}
else
{
/*
Initialize 332 colormap.
*/
i=0;
for (red=0; red < 8; red++)
for (green=0; green < 8; green++)
for (blue=0; blue < 4; blue++)
{
image->colormap[i].red=((unsigned long) (MaxRGB*red)/0x07);
image->colormap[i].green=
((unsigned long) (green*MaxRGB)/0x07);
image->colormap[i].blue=((unsigned long) (MaxRGB*blue)/0x03);
i++;
}
}
}
else
if (max_value != MaxRGB)
{
/*
Compute pixel scaling table.
*/
scale=(Quantum *) AllocateMemory((max_value+1)*sizeof(Quantum));
if (scale == (Quantum *) NULL)
ReaderExit(ResourceLimitWarning,"Memory allocation failed",image);
for (i=0; i <= (int) max_value; i++)
scale[i]=(Quantum) ((i*MaxRGB+(max_value >> 1))/max_value);
}
/*
Convert PNM pixels to runlength-encoded MIFF packets.
*/
switch (format)
{
case '1':
{
/*
Convert PBM image to pixel packets.
*/
for (y=0; y < (int) image->rows; y++)
{
q=SetPixelCache(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) image->columns; x++)
{
index=!PNMInteger(image,2);
image->indexes[x]=index;
*q++=image->colormap[index];
}
if (!SyncPixelCache(image))
break;
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(LoadImageText,y,image->rows);
}
break;
}
case '2':
{
/*
Convert PGM image to pixel packets.
*/
for (y=0; y < (int) image->rows; y++)
{
q=SetPixelCache(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) image->columns; x++)
{
index=PNMInteger(image,10);
image->indexes[x]=index;
*q++=image->colormap[index];
}
if (!SyncPixelCache(image))
break;
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(LoadImageText,y,image->rows);
}
break;
}
case '3':
{
/*
Convert PNM image to pixel packets.
*/
for (y=0; y < (int) image->rows; y++)
{
q=SetPixelCache(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) image->columns; x++)
{
red=PNMInteger(image,10);
green=PNMInteger(image,10);
blue=PNMInteger(image,10);
if (scale != (Quantum *) NULL)
{
red=scale[red];
green=scale[green];
blue=scale[blue];
}
q->red=red;
q->green=green;
q->blue=blue;
q++;
}
if (!SyncPixelCache(image))
break;
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(LoadImageText,y,image->rows);
}
break;
}
case '4':
{
unsigned char
bit,
byte;
/*
Convert PBM raw image to pixel packets.
*/
for (y=0; y < (int) image->rows; y++)
{
q=SetPixelCache(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
break;
bit=0;
byte=0;
for (x=0; x < (int) image->columns; x++)
{
if (bit == 0)
byte=ReadByte(image);
index=(byte & 0x80) ? 0 : 1;
image->indexes[x]=index;
*q++=image->colormap[index];
bit++;
if (bit == 8)
bit=0;
byte<<=1;
}
if (!SyncPixelCache(image))
break;
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(LoadImageText,y,image->rows);
}
break;
}
case '5':
case '7':
{
/*
Convert PGM raw image to pixel packets.
*/
packets=image->depth <= 8 ? 1 : 2;
pixels=(unsigned char *) AllocateMemory(packets*image->columns);
if (pixels == (unsigned char *) NULL)
ReaderExit(CorruptImageWarning,"Unable to allocate memory",image);
for (y=0; y < (int) image->rows; y++)
{
status=ReadBlob(image,packets*image->columns,pixels);
if (status == False)
ReaderExit(CorruptImageWarning,"Unable to read image data",image);
p=pixels;
q=SetPixelCache(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) image->columns; x++)
{
if (image->depth <= 8)
index=(*p++);
else
{
index=(*p++) << 8;
index|=(*p++);
}
if (index >= image->colors)
ReaderExit(CorruptImageWarning,"invalid colormap index",image);
image->indexes[x]=index;
*q++=image->colormap[index];
}
if (!SyncPixelCache(image))
break;
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(LoadImageText,y,image->rows);
}
FreeMemory(pixels);
break;
}
case '6':
{
/*
Convert PNM raster image to pixel packets.
*/
packets=image->depth <= 8 ? 3 : 6;
pixels=(unsigned char *) AllocateMemory(packets*image->columns);
if (pixels == (unsigned char *) NULL)
ReaderExit(CorruptImageWarning,"Unable to allocate memory",image);
for (y=0; y < (int) image->rows; y++)
{
status=ReadBlob(image,packets*image->columns,pixels);
if (status == False)
ReaderExit(CorruptImageWarning,"Unable to read image data",image);
p=pixels;
q=SetPixelCache(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) image->columns; x++)
{
if (image->depth <= 8)
{
red=(*p++);
green=(*p++);
blue=(*p++);
}
else
{
red=(*p++) << 8;
red|=(*p++);
green=(*p++) << 8;
green|=(*p++);
blue=(*p++) << 8;
blue|=(*p++);
}
if (scale != (Quantum *) NULL)
{
red=scale[red];
green=scale[green];
blue=scale[blue];
}
q->red=red;
q->green=green;
q->blue=blue;
q++;
}
if (!SyncPixelCache(image))
break;
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(LoadImageText,y,image->rows);
}
FreeMemory(pixels);
handler=SetMonitorHandler((MonitorHandler) NULL);
(void) SetMonitorHandler(handler);
break;
}
default:
ReaderExit(CorruptImageWarning,"Not a PNM image file",image);
}
if (scale != (Quantum *) NULL)
FreeMemory(scale);
if (EOFBlob(image))
MagickWarning(CorruptImageWarning,"not enough pixels",image->filename);
/*
Proceed to next image.
*/
if (image_info->subrange != 0)
if (image->scene >= (image_info->subimage+image_info->subrange-1))
break;
if ((format == '1') || (format == '2') || (format == '3'))
do
{
/*
Skip to end of line.
*/
status=ReadBlob(image,1,&format);
if (status == False)
break;
} while (format != '\n');
status=ReadBlob(image,1,(char *) &format);
if ((status == True) && (format == 'P'))
{
/*
Allocate next image structure.
*/
AllocateNextImage(image_info,image);
if (image->next == (Image *) NULL)
{
DestroyImages(image);
return((Image *) NULL);
}
image=image->next;
ProgressMonitor(LoadImagesText,TellBlob(image),image->filesize);
}
} while ((status == True) && (format == 'P'));
while (image->previous != (Image *) NULL)
image=image->previous;
CloseBlob(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Procedure WritePNMImage writes an image to a file in the PNM rasterfile
% format.
%
% The format of the WritePNMImage method is:
%
% unsigned int WritePNMImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o status: Method WritePNMImage return True if the image is written.
% False is returned is there is a memory shortage or if the image file
% fails to write.
%
% o image_info: Specifies a pointer to an ImageInfo structure.
%
% o image: A pointer to a Image structure.
%
%
*/
Export unsigned int WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
*magick;
int
y;
register int
i,
j,
x;
register PixelPacket
*p;
unsigned char
format;
unsigned int
scene,
status;
unsigned short
index;
/*
Open output image file.
*/
status=OpenBlob(image_info,image,WriteBinaryType);
if (status == False)
WriterExit(FileOpenWarning,"Unable to open file",image);
scene=0;
do
{
/*
Promote/Demote image based on image type.
*/
TransformRGBImage(image,RGBColorspace);
(void) IsPseudoClass(image);
if (Latin1Compare(image_info->magick,"PPM") == 0)
image->class=DirectClass;
magick=(char *) image_info->magick;
if (((Latin1Compare(magick,"PGM") == 0) && !IsGrayImage(image)) ||
((Latin1Compare(magick,"PBM") == 0) && !IsMonochromeImage(image)))
{
QuantizeInfo
quantize_info;
GetQuantizeInfo(&quantize_info);
quantize_info.number_colors=MaxRGB+1;
if (Latin1Compare(image_info->magick,"PBM") == 0)
quantize_info.number_colors=2;
quantize_info.dither=image_info->dither;
quantize_info.colorspace=GRAYColorspace;
(void) QuantizeImage(&quantize_info,image);
}
/*
Write PNM file header.
*/
if (!IsPseudoClass(image) && !IsGrayImage(image))
{
/*
Full color PNM image.
*/
format='6';
if ((image_info->compression == NoCompression) || (image->depth > 8))
format='3';
}
else
{
/*
Colormapped PNM image.
*/
format='6';
if ((image_info->compression == NoCompression) || (image->depth > 8))
format='3';
if ((Latin1Compare(magick,"PPM") != 0) && IsGrayImage(image))
{
/*
Grayscale PNM image.
*/
format='5';
if ((image_info->compression == NoCompression) ||
(image->depth > 8))
format='2';
if (Latin1Compare(magick,"PGM") != 0)
if (image->colors == 2)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
}
}
if (Latin1Compare(magick,"P7") == 0)
{
format='7';
(void) strcpy(buffer,"P7 332\n");
}
else
(void) sprintf(buffer,"P%c\n",format);
(void) WriteBlob(image,strlen(buffer),buffer);
if (image->comments != (char *) NULL)
{
register char
*p;
/*
Write comments to file.
*/
(void) WriteByte(image,'#');
for (p=image->comments; *p != '\0'; p++)
{
(void) WriteByte(image,*p);
if ((*p == '\n') && (*(p+1) != '\0'))
(void) WriteByte(image,'#');
}
(void) WriteByte(image,'\n');
}
if (format != '7')
{
(void) sprintf(buffer,"%u %u\n",image->columns,image->rows);
(void) WriteBlob(image,strlen(buffer),buffer);
}
/*
Convert runlength encoded to PNM raster pixels.
*/
switch (format)
{
case '1':
{
register unsigned char
polarity;
/*
Convert image to a PBM image.
*/
polarity=Intensity(image->colormap[0]) > (MaxRGB >> 1);
if (image->colors == 2)
polarity=
Intensity(image->colormap[0]) > Intensity(image->colormap[1]);
i=0;
for (y=0; y < (int) image->rows; y++)
{
if (!GetPixelCache(image,0,y,image->columns,1))
break;
for (x=0; x < (int) image->columns; x++)
{
(void) sprintf(buffer,"%d ",(int) (image->indexes[x] == polarity));
(void) WriteBlob(image,strlen(buffer),buffer);
i++;
if (i == 36)
{
(void) WriteByte(image,'\n');
i=0;
}
}
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(SaveImageText,y,image->rows);
}
break;
}
case '2':
{
/*
Convert image to a PGM image.
*/
(void) sprintf(buffer,"%ld\n",MaxRGB);
(void) WriteBlob(image,strlen(buffer),buffer);
i=0;
for (y=0; y < (int) image->rows; y++)
{
p=GetPixelCache(image,0,y,image->columns,1);
if (p == (PixelPacket *) NULL)
break;
for (x=0; x < (int) image->columns; x++)
{
index=Intensity(*p);
(void) sprintf(buffer,"%d ",index);
(void) WriteBlob(image,strlen(buffer),buffer);
i++;
if (i == 12)
{
(void) WriteByte(image,'\n');
i=0;
}
p++;
}
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(SaveImageText,y,image->rows);
}
break;
}
case '3':
{
/*
Convert image to a PNM image.
*/
(void) sprintf(buffer,"%ld\n",MaxRGB);
(void) WriteBlob(image,strlen(buffer),buffer);
i=0;
for (y=0; y < (int) image->rows; y++)
{
p=GetPixelCache(image,0,y,image->columns,1);
if (p == (PixelPacket *) NULL)
break;
for (x=0; x < (int) image->columns; x++)
{
(void) sprintf(buffer,"%d %d %d ",p->red,p->green,p->blue);
(void) WriteBlob(image,strlen(buffer),buffer);
i++;
if (i == 4)
{
(void) WriteByte(image,'\n');
i=0;
}
p++;
}
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(SaveImageText,y,image->rows);
}
break;
}
case '4':
{
register unsigned char
bit,
byte,
polarity;
/*
Convert image to a PBM image.
*/
polarity=Intensity(image->colormap[0]) > (MaxRGB >> 1);
if (image->colors == 2)
polarity=
Intensity(image->colormap[0]) > Intensity(image->colormap[1]);
for (y=0; y < (int) image->rows; y++)
{
if (!GetPixelCache(image,0,y,image->columns,1))
break;
bit=0;
byte=0;
for (x=0; x < (int) image->columns; x++)
{
byte<<=1;
if (image->indexes[x] == polarity)
byte|=0x01;
bit++;
if (bit == 8)
{
(void) WriteByte(image,byte);
bit=0;
byte=0;
}
p++;
}
if (bit != 0)
(void) WriteByte(image,byte << (8-bit));
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(SaveImageText,y,image->rows);
}
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
(void) sprintf(buffer,"%lu\n",DownScale(MaxRGB));
(void) WriteBlob(image,strlen(buffer),buffer);
for (y=0; y < (int) image->rows; y++)
{
p=GetPixelCache(image,0,y,image->columns,1);
if (p == (PixelPacket *) NULL)
break;
for (x=0; x < (int) image->columns; x++)
{
index=DownScale(Intensity(*p));
(void) WriteByte(image,index);
p++;
}
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(SaveImageText,y,image->rows);
}
break;
}
case '6':
{
register unsigned char
*q;
unsigned char
*pixels;
/*
Allocate memory for pixels.
*/
pixels=(unsigned char *)
AllocateMemory(image->columns*sizeof(PixelPacket));
if (pixels == (unsigned char *) NULL)
WriterExit(ResourceLimitWarning,"Memory allocation failed",image);
/*
Convert image to a PNM image.
*/
(void) sprintf(buffer,"%lu\n",DownScale(MaxRGB));
(void) WriteBlob(image,strlen(buffer),buffer);
for (y=0; y < (int) image->rows; y++)
{
p=GetPixelCache(image,0,y,image->columns,1);
if (p == (PixelPacket *) NULL)
break;
q=pixels;
for (x=0; x < (int) image->columns; x++)
{
*q++=DownScale(p->red);
*q++=DownScale(p->green);
*q++=DownScale(p->blue);
p++;
}
(void) WriteBlob(image,q-pixels,(char *) pixels);
if (image->previous == (Image *) NULL)
if (QuantumTick(y,image->rows))
ProgressMonitor(SaveImageText,y,image->rows);
}
FreeMemory(pixels);
break;
}
case '7':
{
static const short int
dither_red[2][16]=
{
{-16, 4, -1, 11,-14, 6, -3, 9,-15, 5, -2, 10,-13, 7, -4, 8},
{ 15, -5, 0,-12, 13, -7, 2,-10, 14, -6, 1,-11, 12, -8, 3, -9}
},
dither_green[2][16]=
{
{ 11,-15, 7, -3, 8,-14, 4, -2, 10,-16, 6, -4, 9,-13, 5, -1},
{-12, 14, -8, 2, -9, 13, -5, 1,-11, 15, -7, 3,-10, 12, -6, 0}
},
dither_blue[2][16]=
{
{ -3, 9,-13, 7, -1, 11,-15, 5, -4, 8,-14, 6, -2, 10,-16, 4},
{ 2,-10, 12, -8, 0,-12, 14, -6, 3, -9, 13, -7, 1,-11, 15, -5}
};
int
value;
Quantum
pixel;
unsigned short
*blue_map[2][16],
*green_map[2][16],
*red_map[2][16];
/*
Allocate and initialize dither maps.
*/
for (i=0; i < 2; i++)
for (j=0; j < 16; j++)
{
red_map[i][j]=(unsigned short *)
AllocateMemory(256*sizeof(unsigned short));
green_map[i][j]=(unsigned short *)
AllocateMemory(256*sizeof(unsigned short));
blue_map[i][j]=(unsigned short *)
AllocateMemory(256*sizeof(unsigned short));
if ((red_map[i][j] == (unsigned short *) NULL) ||
(green_map[i][j] == (unsigned short *) NULL) ||
(blue_map[i][j] == (unsigned short *) NULL))
WriterExit(ResourceLimitWarning,"Memory allocation failed",image);
}
/*
Initialize dither tables.
*/
for (i=0; i < 2; i++)
for (j=0; j < 16; j++)
for (x=0; x < 256; x++)
{
value=x-16;
if (x < 48)
value=x/2+8;
value+=dither_red[i][j];
red_map[i][j][x]=((value < 0) ? 0 : (value > 255) ? 255 : value);
value=x-16;
if (x < 48)
value=x/2+8;
value+=dither_green[i][j];
green_map[i][j][x]=
((value < 0) ? 0 : (value > 255) ? 255 : value);
value=x-32;
if (x < 112)
value=x/2+24;
value+=2*dither_blue[i][j];
blue_map[i][j][x]=((value < 0) ? 0 : (value > 255) ? 255 : value);
}
/*
Convert image to a P7 image.
*/
(void) strcpy(buffer,"#END_OF_COMMENTS\n");
(void) WriteBlob(image,strlen(buffer),buffer);
(void) sprintf(buffer,"%u %u 255\n",image->columns,image->rows);
(void) WriteBlob(image,strlen(buffer),buffer);
i=0;
j=0;
for (y=0; y < (int) image->rows; y++)
{
p=GetPixelCache(image,0,y,image->columns,1);
if (p == (PixelPacket *) NULL)
break;
for (x=0; x < (int) image->columns; x++)
{
if (!image_info->dither)
pixel=((DownScale(p->red) & 0xe0) |
((DownScale(p->green) & 0xe0) >> 3) |
((DownScale(p->blue) & 0xc0) >> 6));
else
pixel=((red_map[i][j][DownScale(p->red)] & 0xe0) |
((green_map[i][j][DownScale(p->green)] & 0xe0) >> 3) |
((blue_map[i][j][DownScale(p->blue)] & 0xc0) >> 6));
(void) WriteByte(image,pixel);
p++;
j++;
if (j == 16)
j=0;
}
i++;
if (i == 2)
i=0;
if (QuantumTick(y,image->rows))
ProgressMonitor(SaveImageText,y,image->rows);
}
/*
Free allocated memory.
*/
for (i=0; i < 2; i++)
for (j=0; j < 16; j++)
{
FreeMemory(green_map[i][j]);
FreeMemory(blue_map[i][j]);
FreeMemory(red_map[i][j]);
}
break;
}
}
if (image->next == (Image *) NULL)
break;
image=GetNextImage(image);
ProgressMonitor(SaveImagesText,scene++,GetNumberScenes(image));
} while (image_info->adjoin);
if (image_info->adjoin)
while (image->previous != (Image *) NULL)
image=image->previous;
CloseBlob(image);
return(True);
}
| C | CL | 6a3e3c7ed9fdcf4a2830f8737af7809c9b0fbcf60017ad76c4de923e311c1f6b |
/**
* \file appl_generic_power_level_client.c
*
* \brief This file defines the Mesh Generic Power Level Model Application Interface
* - includes Data Structures and Methods for Client.
*/
/*
* Copyright (C) 2018. Mindtree Ltd.
* All rights reserved.
*/
/* --------------------------------------------- Header File Inclusion */
#include "appl_generic_power_level_client.h"
/* --------------------------------------------- Global Definitions */
/* --------------------------------------------- Static Global Variables */
static const char main_generic_power_level_client_options[] = "\n\
======== Generic_Power_Level Client Menu ========\n\
0. Exit. \n\
1. Refresh. \n\
\n\
10. Send Generic Power Default Get. \n\
11. Send Generic Power Default Set. \n\
12. Send Generic Power Default Set Unacknowledged. \n\
13. Send Generic Power Last Get. \n\
14. Send Generic Power Level Get. \n\
15. Send Generic Power Level Set. \n\
16. Send Generic Power Level Set Unacknowledged. \n\
17. Send Generic Power Range Get. \n\
18. Send Generic Power Range Set. \n\
19. Send Generic Power Range Set Unacknowledged. \n\
\n\
20. Get Model Handle. \n\
21. Set Publish Address. \n\
\n\
Your Option ? \0";
/* --------------------------------------------- External Global Variables */
static MS_ACCESS_MODEL_HANDLE appl_generic_power_level_client_model_handle;
/* --------------------------------------------- Function */
/* generic_power_level client application entry point */
void main_generic_power_level_client_operations(void)
{
int choice;
MS_ACCESS_ELEMENT_HANDLE element_handle;
static UCHAR model_initialized = 0x00;
/**
* Register with Access Layer.
*/
if (0x00 == model_initialized)
{
API_RESULT retval;
/* Use Default Element Handle. Index 0 */
element_handle = MS_ACCESS_DEFAULT_ELEMENT_HANDLE;
retval = MS_generic_power_level_client_init
(
element_handle,
&appl_generic_power_level_client_model_handle,
appl_generic_power_level_client_cb
);
if (API_SUCCESS == retval)
{
CONSOLE_OUT(
"Generic Power Level Client Initialized. Model Handle: 0x%04X\n",
appl_generic_power_level_client_model_handle);
}
else
{
CONSOLE_OUT(
"[ERR] Generic Power Level Client Initialization Failed. Result: 0x%04X\n",
retval);
}
model_initialized = 0x01;
}
MS_LOOP_FOREVER()
{
CONSOLE_OUT
("%s", main_generic_power_level_client_options);
CONSOLE_IN
("%d", &choice);
if (choice < 0)
{
CONSOLE_OUT
("*** Invalid Choice. Try Again.\n");
continue;
}
switch (choice)
{
case 0:
return;
case 1:
break;
case 10: /* Send Generic Power Default Get */
appl_send_generic_power_default_get();
break;
case 11: /* Send Generic Power Default Set */
appl_send_generic_power_default_set();
break;
case 12: /* Send Generic Power Default Set Unacknowledged */
appl_send_generic_power_default_set_unacknowledged();
break;
case 13: /* Send Generic Power Last Get */
appl_send_generic_power_last_get();
break;
case 14: /* Send Generic Power Level Get */
appl_send_generic_power_level_get();
break;
case 15: /* Send Generic Power Level Set */
appl_send_generic_power_level_set();
break;
case 16: /* Send Generic Power Level Set Unacknowledged */
appl_send_generic_power_level_set_unacknowledged();
break;
case 17: /* Send Generic Power Range Get */
appl_send_generic_power_range_get();
break;
case 18: /* Send Generic Power Range Set */
appl_send_generic_power_range_set();
break;
case 19: /* Send Generic Power Range Set Unacknowledged */
appl_send_generic_power_range_set_unacknowledged();
break;
case 20: /* Get Model Handle */
appl_generic_power_level_client_get_model_handle();
break;
case 21: /* Set Publish Address */
appl_generic_power_level_client_set_publish_address();
break;
}
}
}
/* Send Generic Power Default Get */
void appl_send_generic_power_default_get(void)
{
API_RESULT retval;
CONSOLE_OUT
(">> Send Generic Power Default Get\n");
retval = MS_generic_power_default_get();
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Power Default Set */
void appl_send_generic_power_default_set(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_POWER_DEFAULT_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Power Default Set\n");
CONSOLE_OUT
("Enter Power (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.power = (UINT16)choice;
retval = MS_generic_power_default_set(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Power Default Set Unacknowledged */
void appl_send_generic_power_default_set_unacknowledged(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_POWER_DEFAULT_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Power Default Set Unacknowledged\n");
CONSOLE_OUT
("Enter Power (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.power = (UINT16)choice;
retval = MS_generic_power_default_set_unacknowledged(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Power Last Get */
void appl_send_generic_power_last_get(void)
{
API_RESULT retval;
CONSOLE_OUT
(">> Send Generic Power Last Get\n");
retval = MS_generic_power_last_get();
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Power Level Get */
void appl_send_generic_power_level_get(void)
{
API_RESULT retval;
CONSOLE_OUT
(">> Send Generic Power Level Get\n");
retval = MS_generic_power_level_get();
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Power Level Set */
void appl_send_generic_power_level_set(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_POWER_LEVEL_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Power Level Set\n");
CONSOLE_OUT
("Enter Power (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.power = (UINT16)choice;
CONSOLE_OUT
("Enter TID (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.tid = (UCHAR)choice;
CONSOLE_OUT
("Enter if optional fields to be send (1 - Yes, 0 - No)\n");
CONSOLE_IN
("%d", &choice);
if(0 == choice)
{
param.optional_fields_present = 0x00;
}
else
{
param.optional_fields_present = 0x01;
CONSOLE_OUT
("Enter Transition Time (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.transition_time = (UCHAR)choice;
CONSOLE_OUT
("Enter Delay (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.delay = (UCHAR)choice;
}
retval = MS_generic_power_level_set(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Power Level Set Unacknowledged */
void appl_send_generic_power_level_set_unacknowledged(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_POWER_LEVEL_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Power Level Set Unacknowledged\n");
CONSOLE_OUT
("Enter Power (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.power = (UINT16)choice;
CONSOLE_OUT
("Enter TID (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.tid = (UCHAR)choice;
CONSOLE_OUT
("Enter if optional fields to be send (1 - Yes, 0 - No)\n");
CONSOLE_IN
("%d", &choice);
if(0 == choice)
{
param.optional_fields_present = 0x00;
}
else
{
param.optional_fields_present = 0x01;
CONSOLE_OUT
("Enter Transition Time (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.transition_time = (UCHAR)choice;
CONSOLE_OUT
("Enter Delay (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.delay = (UCHAR)choice;
}
retval = MS_generic_power_level_set_unacknowledged(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Power Range Get */
void appl_send_generic_power_range_get(void)
{
API_RESULT retval;
CONSOLE_OUT
(">> Send Generic Power Range Get\n");
retval = MS_generic_power_range_get();
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Power Range Set */
void appl_send_generic_power_range_set(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_POWER_RANGE_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Power Range Set\n");
CONSOLE_OUT
("Enter Range Min (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.range_min = (UINT16)choice;
CONSOLE_OUT
("Enter Range Max (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.range_max = (UINT16)choice;
retval = MS_generic_power_range_set(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Power Range Set Unacknowledged */
void appl_send_generic_power_range_set_unacknowledged(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_POWER_RANGE_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Power Range Set Unacknowledged\n");
CONSOLE_OUT
("Enter Range Min (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.range_min = (UINT16)choice;
CONSOLE_OUT
("Enter Range Max (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.range_max = (UINT16)choice;
retval = MS_generic_power_range_set_unacknowledged(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Get Model Handle */
void appl_generic_power_level_client_get_model_handle(void)
{
API_RESULT retval;
MS_ACCESS_MODEL_HANDLE model_handle;
retval = MS_generic_power_level_client_get_model_handle(&model_handle);
if (API_SUCCESS == retval)
{
CONSOLE_OUT
(">> Model Handle 0x%04X\n", model_handle);
}
else
{
CONSOLE_OUT
(">> Get Model Handle Failed. Status 0x%04X\n", retval);
}
return;
}
/* Set Publish Address */
void appl_generic_power_level_client_set_publish_address(void)
{
int choice;
API_RESULT retval;
MS_ACCESS_MODEL_HANDLE model_handle;
MS_ACCESS_PUBLISH_INFO publish_info;
/* Set Publish Information */
EM_mem_set(&publish_info, 0, sizeof(publish_info));
publish_info.addr.use_label = MS_FALSE;
CONSOLE_OUT
("Enter Model Handle (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
model_handle = (UINT16)choice;
CONSOLE_OUT
("Enter Generic_Power_Level client Server Address (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
publish_info.addr.addr = (UINT16)choice;
CONSOLE_OUT
("Enter AppKey Index\n");
CONSOLE_IN
("%x", &choice);
publish_info.appkey_index = choice;
publish_info.remote = MS_FALSE;
retval = MS_access_cm_set_model_publication
(
model_handle,
&publish_info
);
if (API_SUCCESS == retval)
{
CONSOLE_OUT
(">> Publish Address is set Successfully.\n");
}
else
{
CONSOLE_OUT
(">> Failed to set publish address. Status 0x%04X\n", retval);
}
return;
}
/**
* \brief Client Application Asynchronous Notification Callback.
*
* \par Description
* Generic_Power_Level client calls the registered callback to indicate events occurred to the application.
*
* \param [in] handle Model Handle.
* \param [in] opcode Opcode.
* \param [in] data_param Data associated with the event if any or NULL.
* \param [in] data_len Size of the event data. 0 if event data is NULL.
*/
API_RESULT appl_generic_power_level_client_cb
(
/* IN */ MS_ACCESS_MODEL_HANDLE * handle,
/* IN */ UINT32 opcode,
/* IN */ UCHAR * data_param,
/* IN */ UINT16 data_len
)
{
API_RESULT retval;
retval = API_SUCCESS;
CONSOLE_OUT (
"[GENERIC_POWER_LEVEL_CLIENT] Callback. Opcode 0x%04X\n", opcode);
appl_dump_bytes(data_param, data_len);
switch(opcode)
{
case MS_ACCESS_GENERIC_POWER_DEFAULT_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_POWER_DEFAULT_STATUS_OPCODE\n");
}
break;
case MS_ACCESS_GENERIC_POWER_LAST_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_POWER_LAST_STATUS_OPCODE\n");
}
break;
case MS_ACCESS_GENERIC_POWER_LEVEL_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_POWER_LEVEL_STATUS_OPCODE\n");
}
break;
case MS_ACCESS_GENERIC_POWER_RANGE_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_POWER_RANGE_STATUS_OPCODE\n");
}
break;
}
return retval;
}
| C | CL | 2b19b788914c31d53ecd01da1af27d9eb5cbb449e9fbe02e373d08bdce399791 |
/*** headerID = "dirs.h 1.0 (c) 1988 S. Savitzky ***/
/*********************************************************************\
**
** Dirs -- Header file for Directory trees
**
** 880111 SS create from DD/data
** 880419 SS rename from data to dirs
** 880619 SS remove dirs.files
**
\*********************************************************************/
#define NAMELEN 15 /* NOTE: must be at least 1 char longer */
/* than the longest name on the disk */
/* so names will have null at end. */
/* 32+1 handles bsd4.2 Unix, VMS, and Mac. */
/* 14+1 handles iRMX-86, SysV, and MS-DOS */
#ifndef MAXDRIVES
#define MAXDRIVES 26
#endif
/*********************************************************************\
**
** Directory Tree Node
** One would be tempted to call it File, but Dir is less
** likely to get confused with FILE.
**
** isTagged in a directory means that the directory contains
** tagged files (possibly in a subdirectory), and so needs to
** be created when copying the tree.
**
** On the read_file and write_file functions, a count of 0
** closes the file.
**
\*********************************************************************/
typedef enum {unknown, ascii, binary} FileType; /* standard ftypes */
typedef struct _DirRec *Dir;
typedef struct _DirClassRec *DirClass;
typedef struct _DirPart {
unsigned isDir: 1; /* TRUE if is directory */
unsigned isOpen: 1; /* TRUE if has been opened */
unsigned isVisible: 1; /* TRUE if visible on screen */
unsigned isChanged: 1; /* TRUE if file has been written */
ushort ftype; /* ascii/binary/whatever */
ulong size; /* size in bytes */
ulong fsize; /* total file size */
ushort fcount; /* file count if dir, 1 if file */
ushort dcount; /* directory count if dir, 0 if file */
ulong tsize; /* total size of tagged files */
ushort tcount; /* count of tagged files */
ulong time; /* time of last write: Unix format */
/* sec since 1970/01/01.00:00:00 */
char name[NAMELEN];
ulong file; /* handle for open file */
} DirPart;
typedef struct _DirRec {
ObjectPart object;
TreePart tree;
DirPart dir;
} DirRec, *Dir;
typedef struct _DirClassPart {
int name_size;
Dir freelist;
Dir (*read_tree)(); /* (drive) -> root */
Dir (*create_file)(); /* (dir, name, dir) -> new file */
Bool (*open_file)(); /* (dir, string) -> success */
Bool (*close_file)();/* (dir) -> success */
int (*read_file)(); /* (dir, &buf, size) -> count */
int (*write_file)();/* (dir, &buf, size) -> count */
unsigned (*validate)(); /* (dir) -> validate drive */
int (*seek)(); /* (dir, loc) -> success */
long (*tell)(); /* (dir) -> loc */
Bool (*rename)(); /* (dir, name) -> success */
Bool (*unlink)(); /* (dir) -> success */
} DirClassPart;
typedef struct _DirClassRec {
ObjectPart obj;
ObjectClassPart objClass;
TreeClassPart treeClass;
DirClassPart dirClass;
} DirClassRec;
global Class clDir;
#define ISDIR(d) (((Dir)(d)) -> dir.isDir)
#define fFile(d) ((Dir)(d) -> dir.file)
#define dirFreelist(c) (((DirClassRec *)(c)) -> dirClass.freelist)
#define cfReadTree(o) CMETH((o), DirClass, dirClass.read_tree)
#define gCreateFile(o,s,d) METH2((o), DirClass, dirClass.create_file, s, d)
#define gOpenFile(o,s) METH1((o), DirClass, dirClass.open_file, s)
#define gCloseFile(o) METH0((o), DirClass, dirClass.close_file)
#define gReadFile(o,b,n) METH2((o), DirClass, dirClass.read_file, b,n)
#define gWriteFile(o,b,n) METH2((o), DirClass, dirClass.write_file,b,n)
#define gValidate(o) METH0((o), DirClass, dirClass.validate)
#define gSeek(o,l) METH1((o), DirClass, dirClass.seek,l)
#define gTell(o) METH0((o), DirClass, dirClass.tell,l)
#define gRename(o,s) METH1((o), DirClass, dirClass.rename,s)
#define gUnlink(o) METH0((o), DirClass, dirClass.unlink)
/*********************************************************************\
**
** Drives & Other Variables
**
** The dDrives array keeps track of what's in which drive.
** Among other things, it is used to make sure that we don't
** try to read a drive in two different operating systems.
**
** 0 in dWorkingDrive means that a volume from another OS has
** been mounted in that drive, so dWorkingPath is invalid.
**
** dWorkingPath never changes. It's only the root pathname
** for '.' when that's the virtual root.
**
\*********************************************************************/
global Dir dDrives[MAXDRIVES];
global int inUse[MAXDRIVES]; /* actually use count */
global char dWorkingPath[256];
global unsigned dWorkingDrive; /* A = 1, as in DOS; 0 = invalid */
#define dDriveNum(str) (((*(str) == '.') ? *dWorkingPath : *(str)) - 'A')
global VoidFunc dEachNewDir; /* Called on each new Dir when reading */
/* a whole tree. */
extern char *dFtypeName[]; /* Array of filetype names for this app. */
/*********************************************************************\
**
** Functions
**
\*********************************************************************/
global long dTaggedSize(); /* (n) -> size total tagged size */
global long dTag(); /* (n) -> size tag node */
global long dUntag(); /* (n) -> size untag node */
global Dir dReadDirTree(); /* (drive) read a directory tree */
global Dir dReadDosTree(); /* (drive) read tree for a drive */
global Bool dSetWorkingDir(); /* (n) set working directory */
| C | CL | 2fd3428f41cd5f53d8c0a1c8b68149155c3c4da699eb503d1a308ca546c24bf4 |
#include "minifyjpeg_clnt.c"
#include "minifyjpeg_xdr.c"
#include <stdio.h>
#include <stdlib.h>
CLIENT* get_minify_client(char *server){
CLIENT *cl;
/* Your code goes here */
cl = clnt_create(server, JPEG_PROG, JPEG_VER, "tcp");
if (cl == NULL) {
clnt_pcreateerror(server);
}
else {
// Change the default time-out value
struct timeval tv;
tv.tv_sec = 10;
tv.tv_usec = 0;
clnt_control(cl, CLSET_TIMEOUT, (char *)&tv);
}
return cl;
}
/*
The size of the minified file is not known before the call to the library that minimizes it,
therefore this function should allocate the right amount of memory to hold the minimized file
and return it in the last parameter to it
*/
int minify_via_rpc(CLIENT *cl, void* src_val, size_t src_len, size_t *dst_len, void **dst_val){
/*Your code goes here */
// Call rpc to get:
// 1. size of the minified file
// 2. Allocate memory to hold the minified file contents
// 3. Populate minified file contents to allocated memory
// 4. Return dst_val
jpeg_in in;
jpeg_out out;
memset(&in, 0, sizeof(in));
memset(&out, 0, sizeof(out));
enum clnt_stat stat = 0;
in.data.data_val = (char *)src_val;
in.data.data_len = (u_int)src_len;
// Allocate memory for the minified file, since we are "down-sizing" src_len is definitely large enough.
out.data.data_val = (char *)malloc(src_len);
// RPC.
stat = jpeg_minify_1(in, &out, cl);
if(stat == RPC_TIMEDOUT) {
return stat;
}
*dst_len = (size_t)(out.data.data_len);
*dst_val = (char *)(out.data.data_val);
return stat;
}
| C | CL | d3889b40d3cf223ac98b1197a3c0b15cc37cd490d7a9bc0bfd8ce5e9118b2203 |
#ifndef CACHEGRAND_STORAGE_DB_H
#define CACHEGRAND_STORAGE_DB_H
#ifdef __cplusplus
extern "C" {
#endif
#include "storage/channel/storage_buffered_channel.h"
//#define STORAGE_DB_SHARD_VERSION 1
//#define STORAGE_DB_SHARD_MAGIC_NUMBER_HIGH 0x4341434845475241
//#define STORAGE_DB_SHARD_MAGIC_NUMBER_LOW 0x5241000000000000
#define STORAGE_DB_SHARD_VERSION (1)
#define STORAGE_DB_CHUNK_MAX_SIZE ((64 * 1024) - 1)
#define STORAGE_DB_WORKERS_MAX (1024)
#define STORAGE_DB_MAX_USER_DATABASES (UINT8_MAX)
#define STORAGE_DB_KEYS_EVICTION_BITONIC_SORT_16_ELEMENTS_ARRAY_LENGTH (64)
#define STORAGE_DB_KEYS_EVICTION_EVICT_FIRST_N_KEYS (5)
#define STORAGE_DB_KEYS_EVICTION_ITER_MAX_DISTANCE (5000)
#define STORAGE_DB_KEYS_EVICTION_ITER_MAX_SEARCH_ATTEMPTS (5)
// This magic value defines the size of the ring buffer used to keep in memory data long enough to be sure they are not
// being in use anymore.
#define STORAGE_DB_WORKER_ENTRY_INDEX_RING_BUFFER_SIZE 512
#define STORAGE_DB_ENTRY_NO_EXPIRY (0)
typedef uint32_t storage_db_database_number_t;
typedef uint16_t storage_db_chunk_index_t;
typedef uint16_t storage_db_chunk_length_t;
typedef uint32_t storage_db_chunk_offset_t;
typedef uint32_t storage_db_shard_index_t;
typedef uint64_t storage_db_create_time_ms_t;
typedef uint64_t storage_db_last_access_time_ms_t;
typedef uint64_t storage_db_snapshot_time_ms_t;
typedef int64_t storage_db_expiry_time_ms_t;
struct storage_db_keys_eviction_kv_list_entry {
uint64_t value;
uint64_t key;
} __attribute__((__aligned__(16)));
typedef struct storage_db_keys_eviction_kv_list_entry storage_db_keys_eviction_kv_list_entry_t;
struct storage_db_config_limits {
struct {
uint64_t soft_limit;
uint64_t hard_limit;
} data_size;
struct {
hashtable_bucket_count_t soft_limit;
hashtable_bucket_count_t hard_limit;
} keys_count;
};
typedef struct storage_db_config_limits storage_db_config_limits_t;
struct storage_db_keys_eviction_list_entry {
uint16_t key_size;
uint32_t accesses_counters;
char *key;
storage_db_last_access_time_ms_t last_access_time_ms;
storage_db_expiry_time_ms_t expiry_time_ms;
};
typedef struct storage_db_keys_eviction_list_entry storage_db_keys_eviction_list_entry_t;
struct storage_db_counters_slots_bitmap_and_index {
slots_bitmap_mpmc_t *slots_bitmap;
uint64_t index;
};
typedef struct storage_db_counters_slots_bitmap_and_index storage_db_counters_slots_bitmap_and_index_t;
enum storage_db_backend_type {
STORAGE_DB_BACKEND_TYPE_UNKNOWN = 0,
STORAGE_DB_BACKEND_TYPE_MEMORY = 1,
STORAGE_DB_BACKEND_TYPE_FILE = 2,
};
typedef enum storage_db_backend_type storage_db_backend_type_t;
enum storage_db_entry_index_value_type {
STORAGE_DB_ENTRY_INDEX_VALUE_TYPE_UNKNOWN = 1,
STORAGE_DB_ENTRY_INDEX_VALUE_TYPE_STRING = 2,
STORAGE_DB_ENTRY_INDEX_VALUE_TYPE_LIST = 3,
STORAGE_DB_ENTRY_INDEX_VALUE_TYPE_HASHSET = 4,
STORAGE_DB_ENTRY_INDEX_VALUE_TYPE_SORTEDSET = 5
};
typedef enum storage_db_entry_index_value_type storage_db_entry_index_value_type_t;
struct storage_db_config_snapshot {
bool enabled;
uint64_t interval_ms;
uint64_t min_keys_changed;
uint64_t min_data_changed;
char *path;
uint64_t rotation_max_files;
bool snapshot_at_shutdown;
};
typedef struct storage_db_config_snapshot storage_db_config_snapshot_t;
// general config parameters to initialize and use the internal storage db (e.g. storage backend, amount of memory for
// the hashtable, other optional stuff)
typedef struct storage_db_config storage_db_config_t;
struct storage_db_config {
storage_db_backend_type_t backend_type;
storage_db_config_limits_t limits;
storage_db_config_snapshot_t snapshot;
uint32_t max_user_databases;
struct {
storage_db_expiry_time_ms_t default_ms;
storage_db_expiry_time_ms_t max_ms;
} enforced_ttl;
union {
struct {
char *basedir_path;
size_t shard_size_mb;
} file;
} backend;
};
typedef struct storage_db_shard storage_db_shard_t;
struct storage_db_shard {
storage_db_shard_index_t index;
size_t offset;
size_t size;
storage_channel_t *storage_channel;
char* path;
uint32_t version;
timespec_t creation_time;
};
typedef struct storage_db_worker storage_db_worker_t;
struct storage_db_worker {
storage_db_shard_t *active_shard;
ring_bounded_queue_spsc_voidptr_t *deleted_entry_index_ring_buffer;
double_linked_list_t *deleting_entry_index_list;
};
typedef struct storage_db_counters storage_db_counters_t;
struct storage_db_counters {
int64_t keys_count;
int64_t data_size;
int64_t keys_changed;
int64_t data_changed;
};
typedef struct storage_db_counters_global_and_per_db storage_db_counters_global_and_per_db_t;
struct storage_db_counters_global_and_per_db {
storage_db_counters_t global;
hashtable_spsc_t *per_db;
};
enum storage_db_snapshot_status {
STORAGE_DB_SNAPSHOT_STATUS_NONE = 0,
STORAGE_DB_SNAPSHOT_STATUS_IN_PROGRESS,
STORAGE_DB_SNAPSHOT_STATUS_BEING_FINALIZED,
STORAGE_DB_SNAPSHOT_STATUS_COMPLETED,
STORAGE_DB_SNAPSHOT_STATUS_FAILED,
STORAGE_DB_SNAPSHOT_STATUS_FAILED_DURING_PREPARATION,
};
typedef enum storage_db_snapshot_status storage_db_snapshot_status_t;
typedef _Volatile(storage_db_snapshot_status_t) storage_db_snapshot_status_volatile_t;
// contains the necessary information to manage the db, holds a pointer to storage_db_config required during the
// the initialization
typedef struct storage_db storage_db_t;
struct storage_db {
struct {
storage_db_shard_t **active_per_worker;
double_linked_list_t *opened_shards;
storage_db_shard_index_t new_index;
spinlock_lock_volatile_t write_spinlock;
} shards;
struct {
spinlock_lock_t spinlock;
storage_db_database_number_t current_database_number;
uint64_t iteration;
uint64_volatile_t next_run_time_ms;
uint64_volatile_t start_time_ms;
uint64_volatile_t end_time_ms;
uint64_volatile_t progress_reported_at_ms;
bool_volatile_t in_preparation;
storage_db_snapshot_status_volatile_t status;
uint64_volatile_t block_index;
bool_volatile_t running;
bool_volatile_t storage_channel_opened;
storage_buffered_channel_t *storage_buffered_channel;
queue_mpmc_t *entry_index_to_be_deleted_queue;
uint64_t keys_changed_at_start;
uint64_t data_changed_at_start;
#if DEBUG == 1
uint64_volatile_t parallel_runs;
#endif
char *path;
struct {
uint64_t data_written;
uint64_t keys_written;
} stats;
} snapshot;
hashtable_t *hashtable;
storage_db_config_t *config;
storage_db_worker_t *workers;
uint16_t workers_count;
storage_db_config_limits_t limits;
slots_bitmap_mpmc_t *counters_slots_bitmap;
storage_db_counters_global_and_per_db_t counters[STORAGE_DB_WORKERS_MAX];
};
typedef struct storage_db_chunk_info storage_db_chunk_info_t;
struct storage_db_chunk_info {
union {
struct {
storage_channel_t *shard_storage_channel;
storage_db_chunk_offset_t chunk_offset;
} file;
struct {
void *chunk_data;
} memory;
};
storage_db_chunk_length_t chunk_length;
};
typedef union storage_db_entry_index_status storage_db_entry_index_status_t;
union storage_db_entry_index_status {
uint64_volatile_t _cas_wrapper;
struct {
uint32_volatile_t readers_counter:31;
bool_volatile_t deleted:1;
uint32_volatile_t accesses_counter;
};
};
typedef struct storage_db_chunk_sequence storage_db_chunk_sequence_t;
struct storage_db_chunk_sequence {
storage_db_chunk_index_t count;
storage_db_chunk_info_t *sequence;
size_t size;
};
typedef struct storage_db_entry_index storage_db_entry_index_t;
struct storage_db_entry_index {
storage_db_entry_index_status_t status;
storage_db_database_number_t database_number;
storage_db_entry_index_value_type_t value_type:8;
storage_db_create_time_ms_t created_time_ms;
storage_db_expiry_time_ms_t expiry_time_ms;
storage_db_last_access_time_ms_t last_access_time_ms;
storage_db_snapshot_time_ms_t snapshot_time_ms;
storage_db_chunk_sequence_t key;
storage_db_chunk_sequence_t value;
};
typedef struct storage_db_op_rmw_transaction storage_db_op_rmw_status_t;
struct storage_db_op_rmw_transaction {
hashtable_mcmp_op_rmw_status_t hashtable;
transaction_t *transaction;
storage_db_entry_index_t *current_entry_index;
bool delete_entry_index_on_abort;
};
typedef struct storage_db_key_and_key_length storage_db_key_and_key_length_t;
struct storage_db_key_and_key_length {
char *key;
size_t key_size;
};
void storage_db_counters_sum_global(
storage_db_t *storage_db,
storage_db_counters_t *counters);
void storage_db_counters_sum_per_db(
storage_db_t *storage_db,
storage_db_database_number_t database_number,
storage_db_counters_t *counters);
char *storage_db_shard_build_path(
char *basedir_path,
storage_db_shard_index_t shard_index);
storage_db_config_t* storage_db_config_new();
void storage_db_config_free(
storage_db_config_t* config);
storage_db_t* storage_db_new(
storage_db_config_t *config,
uint32_t workers_count);
storage_db_shard_t *storage_db_new_active_shard(
storage_db_t *db,
uint32_t worker_index);
storage_db_shard_t *storage_db_new_active_shard_per_current_worker(
storage_db_t *db);
storage_db_shard_t* storage_db_shard_new(
storage_db_shard_index_t index,
char *path,
uint32_t shard_size_mb);
storage_channel_t *storage_db_shard_open_or_create_file(
char *path,
bool create);
bool storage_db_open(
storage_db_t *db);
bool storage_db_close(
storage_db_t *db);
void storage_db_free(
storage_db_t *db,
uint32_t workers_count);
storage_db_shard_t *storage_db_worker_active_shard(
storage_db_t *db);
ring_bounded_queue_spsc_voidptr_t *storage_db_worker_deleted_entry_index_ring_buffer(
storage_db_t *db);
void storage_db_worker_garbage_collect_deleting_entry_index_when_no_readers(
storage_db_t *db);
double_linked_list_t *storage_db_worker_deleting_entry_index_list(
storage_db_t *db);
bool storage_db_shard_new_is_needed(
storage_db_shard_t *shard,
size_t chunk_length);
bool storage_db_chunk_data_pre_allocate(
storage_db_t *db,
storage_db_chunk_info_t *chunk_info,
size_t chunk_length);
void storage_db_chunk_data_free(
storage_db_t *db,
storage_db_chunk_info_t *chunk_info);
storage_db_entry_index_t *storage_db_entry_index_new();
void storage_db_entry_index_chunks_free(
storage_db_t *db,
storage_db_entry_index_t *entry_index);
void storage_db_entry_index_free(
storage_db_t *db,
storage_db_entry_index_t *entry_index);
void storage_db_entry_index_touch(
storage_db_entry_index_t *entry_index);
storage_db_entry_index_t *storage_db_entry_index_ring_buffer_new(
storage_db_t *db);
void storage_db_entry_index_ring_buffer_free(
storage_db_t *db,
storage_db_entry_index_t *entry_index);
bool storage_db_entry_chunk_can_read_from_memory(
storage_db_t *db,
storage_db_chunk_info_t *chunk_info);
char* storage_db_entry_chunk_read_fast_from_memory(
storage_db_t *db,
storage_db_chunk_info_t *chunk_info);
bool storage_db_chunk_read(
storage_db_t *db,
storage_db_chunk_info_t *chunk_info,
char *buffer,
off_t offset,
size_t length);
bool storage_db_chunk_write(
storage_db_t *db,
storage_db_chunk_info_t *chunk_info,
off_t chunk_offset,
char *buffer,
size_t buffer_length);
size_t storage_db_chunk_sequence_calculate_chunk_count(
size_t size);
size_t storage_db_chunk_sequence_allowed_max_size();
bool storage_db_chunk_sequence_is_size_allowed(
size_t size);
bool storage_db_chunk_sequence_allocate(
storage_db_t *db,
storage_db_chunk_sequence_t *chunk_sequence,
size_t size);
storage_db_chunk_info_t *storage_db_chunk_sequence_get(
storage_db_chunk_sequence_t *chunk_sequence,
storage_db_chunk_index_t chunk_index);
char *storage_db_get_chunk_data(
storage_db_t *db,
storage_db_chunk_info_t *chunk_info,
bool *allocated_new_buffer);
void storage_db_chunk_sequence_free_chunks(
storage_db_t *db,
storage_db_chunk_sequence_t *sequence);
void storage_db_entry_index_status_increase_readers_counter(
storage_db_entry_index_t* entry_index,
storage_db_entry_index_status_t *old_status);
void storage_db_entry_index_status_decrease_readers_counter(
storage_db_entry_index_t* entry_index,
storage_db_entry_index_status_t *old_status);
void storage_db_entry_index_status_set_deleted(
storage_db_entry_index_t* entry_index,
bool deleted,
storage_db_entry_index_status_t *old_status);
storage_db_entry_index_t *storage_db_get_entry_index(
storage_db_t *db,
storage_db_database_number_t database_number,
char *key,
size_t key_length);
bool storage_db_entry_index_is_expired(
storage_db_entry_index_t *entry_index);
int64_t storage_db_entry_index_ttl_ms(
storage_db_entry_index_t *entry_index);
storage_db_entry_index_t *storage_db_get_entry_index_for_read_prep(
storage_db_t *db,
storage_db_database_number_t database_number,
char *key,
size_t key_length,
storage_db_entry_index_t *entry_index);
storage_db_entry_index_t *storage_db_get_entry_index_for_read_prep_no_expired_eviction(
storage_db_t *db,
storage_db_entry_index_t *entry_index);
storage_db_entry_index_t *storage_db_get_entry_index_for_read(
storage_db_t *db,
storage_db_database_number_t database_number,
char *key,
size_t key_length);
bool storage_db_set_entry_index(
storage_db_t *db,
storage_db_database_number_t database_number,
char *key,
size_t key_length,
storage_db_entry_index_t *entry_index);
bool storage_db_op_set(
storage_db_t *db,
storage_db_database_number_t database_number,
char *key,
size_t key_length,
storage_db_entry_index_value_type_t value_type,
storage_db_chunk_sequence_t *value_chunk_sequence,
storage_db_expiry_time_ms_t expiry_time_ms);
bool storage_db_op_rmw_begin(
storage_db_t *db,
transaction_t *transaction,
storage_db_database_number_t database_number,
char *key,
size_t key_length,
storage_db_op_rmw_status_t *rmw_status,
storage_db_entry_index_t **current_entry_index);
storage_db_entry_index_t *storage_db_op_rmw_current_entry_index_prep_for_read(
storage_db_t *db,
storage_db_op_rmw_status_t *rmw_status,
storage_db_entry_index_t *entry_index);
bool storage_db_op_rmw_commit_metadata(
storage_db_t *db,
storage_db_op_rmw_status_t *rmw_status);
bool storage_db_op_rmw_commit_update(
storage_db_t *db,
storage_db_op_rmw_status_t *rmw_status,
storage_db_entry_index_value_type_t value_type,
storage_db_chunk_sequence_t *value_chunk_sequence,
storage_db_expiry_time_ms_t expiry_time_ms);
void storage_db_op_rmw_commit_rename(
storage_db_t *db,
storage_db_op_rmw_status_t *rmw_status_source,
storage_db_op_rmw_status_t *rmw_status_destination);
void storage_db_op_rmw_commit_delete(
storage_db_t *db,
storage_db_op_rmw_status_t *rmw_status);
void storage_db_op_rmw_abort(
storage_db_t *db,
storage_db_op_rmw_status_t *rmw_status);
bool storage_db_op_delete(
storage_db_t *db,
storage_db_database_number_t database_number,
char *key,
size_t key_length);
bool storage_db_op_delete_by_index(
storage_db_t *db,
storage_db_database_number_t database_number,
hashtable_bucket_index_t bucket_index);
bool storage_db_op_delete_by_index_all_databases(
storage_db_t *db,
hashtable_bucket_index_t bucket_index,
storage_db_entry_index_t **out_current_entry_index);
char *storage_db_op_random_key(
storage_db_t *db,
storage_db_database_number_t database_number,
hashtable_key_length_t *key_size);
int64_t storage_db_op_get_keys_count_per_db(
storage_db_t *db,
storage_db_database_number_t database_number);
int64_t storage_db_op_get_data_size_per_db(
storage_db_t *db,
storage_db_database_number_t database_number);
int64_t storage_db_op_get_keys_count_global(
storage_db_t *db);
int64_t storage_db_op_get_data_size_global(
storage_db_t *db);
bool storage_db_op_flush_sync(
storage_db_t *db,
storage_db_database_number_t database_number);
storage_db_key_and_key_length_t *storage_db_op_get_keys(
storage_db_t *db,
storage_db_database_number_t database_number,
uint64_t cursor,
uint64_t count,
char *pattern,
size_t pattern_length,
uint64_t *keys_count,
uint64_t *cursor_next);
void storage_db_free_key_and_key_length_list(
storage_db_key_and_key_length_t *keys,
uint64_t keys_count);
void storage_db_keys_eviction_bitonic_sort_16_elements(
storage_db_keys_eviction_kv_list_entry_t *kv);
uint8_t storage_db_keys_eviction_run_worker(
storage_db_t *db,
storage_db_counters_t *counters,
bool only_ttl,
config_database_keys_eviction_policy_t policy);
static inline bool storage_db_keys_eviction_should_run(
storage_db_t *db,
storage_db_counters_t *counters) {
if (counters->keys_count == 0) {
return false;
}
if (db->limits.keys_count.soft_limit > 0 && counters->keys_count > db->limits.keys_count.soft_limit) {
return true;
}
if (db->limits.data_size.soft_limit > 0 && counters->data_size > db->limits.data_size.soft_limit) {
return true;
}
return false;
}
static inline double storage_db_keys_eviction_calculate_close_to_hard_limit_percentage(
storage_db_t *db,
storage_db_counters_t *counters) {
double keys_count_close_to_hard_limit_percentage = 0;
double data_size_close_to_hard_limit_percentage = 0;
if (db->limits.keys_count.soft_limit == 0 && db->limits.data_size.soft_limit == 0) {
return 0;
}
if (db->limits.keys_count.soft_limit > 0 && counters->keys_count > db->limits.keys_count.soft_limit) {
keys_count_close_to_hard_limit_percentage =
(double)(counters->keys_count - db->limits.keys_count.soft_limit) /
(double)(db->limits.keys_count.hard_limit - db->limits.keys_count.soft_limit);
}
if (db->limits.data_size.soft_limit > 0 && counters->data_size > db->limits.data_size.soft_limit) {
data_size_close_to_hard_limit_percentage =
(double)(counters->data_size - db->limits.data_size.soft_limit) /
(double)(db->limits.data_size.hard_limit - db->limits.data_size.soft_limit);
}
return keys_count_close_to_hard_limit_percentage > data_size_close_to_hard_limit_percentage ?
keys_count_close_to_hard_limit_percentage : data_size_close_to_hard_limit_percentage;
}
#ifdef __cplusplus
}
#endif
#endif //CACHEGRAND_STORAGE_DB_H
| C | CL | 53b0df7e9ec44957e30405b99dffe13bf0bf857e0f9aeed38f9dcfed4394ce3c |
#ifndef clox_vm_h
#define clox_vm_h
#include "object.h"
#include "table.h"
#include "value.h"
#define FRAMES_MAX 64
#define STACK_MAX (FRAMES_MAX * UINT8_COUNT)
typedef struct {
ObjClosure* closure;
uint8_t* ip;
Value* slots;
} CallFrame;
typedef struct {
CallFrame frames[FRAMES_MAX];
int frameCount;
Value stack[STACK_MAX];
Value* stackTop;
Table strings;
Table globals;
ObjUpvalue* openUpvalues;
size_t bytesAllocated;
size_t nextGC;
Obj* objects;
int grayCount;
int grayCapacity;
Obj** grayStack;
} VM;
typedef enum {
INTERPRET_OK,
INTERPRET_COMPILE_ERROR,
INTERPRET_RUNTIME_ERROR,
} InterpretResult;
extern VM vm;
void initVM();
void freeVM();
InterpretResult interpret(const char* source);
void push(Value value);
Value pop();
#endif
| C | CL | 13cf40a058de036b0ec30267d7160ea44c8471bc462e5964a0119d630f811cf8 |
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "lizard.h"
#include "order.h"
#include "lizgame.h"
#include "lizhex.h"
#include "lizmisc.h"
/* ----------------------------------------------------------------------
--
-- Prototypes
--
---------------------------------------------------------------------- */
int main (int argc, char *argv []);
int lizard_pop_growth (World *, int present_pop, int max_pop);
int ProcessHex(World *, hex_t world_hex);
/* ----------------------------------------------------------------------
--
-- lizard_pop_growth
--
---------------------------------------------------------------------- */
int lizard_pop_growth (World *world, int present_pop, int max_pop)
{
float fwork,
fwork2;
int work;
if (present_pop > max_pop)
{
if (present_pop - max_pop < 1)
return (1);
else
return (-((present_pop - max_pop) / 2));
} else {
fwork = ((float) present_pop / (float) max_pop);
fwork2 = 0.6 - ((fwork / 0.10) * 0.05);
if (world->flags & LZ_SPAWN)
fwork2 *= 10.0;
work = (float) present_pop * fwork2;
}
return (work);
}
/* ---------------------------------------------------------------------- */
int ProcessHex(World *world, hex_t world_hex)
{
FILE *fptr;
char work_string [80];
int work3,
work4,
hex_change;
hex_change = 0;
xy_to_string (world_hex.x, world_hex.y, work_string);
if (world_hex.turns_undisturbed > 0)
{
world_hex.turns_undisturbed --;
hex_change = 1;
}
if (world_hex.lizards_immobile > 0)
{
if (world_hex.lizards_immobile == 3)
world_hex.lizards_immobile = 0;
else
world_hex.lizards_immobile -= 1;
hex_change = 1;
}
if ((world_hex.terrain == CURSED) && (world->turn > 0))
{
if (lizards_in_hex (&world_hex) > 0)
{
open_player_mesg (world_hex.hex_owner, &fptr);
work3 = (float) lizards_in_hex (&world_hex) * CURSED_KILL_LEVEL;
if (work3 < 1) work3 = 1;
fprintf (fptr, "Cursed: %s, %d %d %d %d %d %d\n",
work_string,
lizards_in_hex(&world_hex),
world_hex.red_lizards,
world_hex.green_lizards,
world_hex.grey_lizards,
world_hex.black_lizards,
world_hex.yellow_lizards);
kill_lizards_xy (&world_hex, work3);
hex_change = 1;
fclose (fptr);
}
for (work3 = 0; work3 < world->num_spies; work3 ++)
if (world->spylist [work3]->x_hex == world_hex.x &&
world->spylist [work3]->y_hex == world_hex.y)
{
open_player_mesg (world->spylist [work3]->player, &fptr);
fprintf (fptr, "SpyCursed: %s\n",
work_string);
world->spylist [work3]->player = 0;
fclose (fptr);
}
}
if (world_hex.terrain == DEN || world_hex.terrain == HOME_DEN)
{
work3 = terrain_adjacent (world, world_hex.x, world_hex.y, FERTILE);
if (world_hex.hex_owner > 0)
open_player_mesg (world_hex.hex_owner, &fptr);
else
fptr = NULL;
if (work3 == 0)
{
if (world->turn > 0)
{
if (world_hex.den_lizard_type == 0)
{
if (fptr != NULL)
fprintf (fptr, "NomadStarve: %s %d",
work_string,
world_hex.lizard_pop);
world_hex.lizard_pop = 0;
hex_change = 1;
world_hex.terrain = RUIN;
}
else
{
work4 = ((double) world_hex.lizard_pop *
(DEN_STARVE_LEVEL + (world_hex.turns_den_hungry *
DEN_INCREASE_STARVE_LEVEL)));
if ((world_hex.lizard_pop - work4) < MINIMUM_POP_LEVEL)
{
world_hex.terrain = RUIN;
world_hex.lizard_pop = 0;
if (world_hex.hex_owner == 0)
{
world_hex.red_lizards = 0;
world_hex.green_lizards = 0;
world_hex.grey_lizards = 0;
world_hex.black_lizards = 0;
world_hex.yellow_lizards = 0;
}
else
{
if (world_hex.terrain == HOME_DEN)
fprintf (fptr, "HomeDenStarveRuin: %s %d\n",
work_string,
world_hex.den_lizard_type);
else
fprintf (fptr, "DenStarveRuin: %s %d\n",
work_string,
world_hex.den_lizard_type);
}
world_hex.den_lizard_type = 0;
world_hex.turns_den_hungry = 0;
hex_change = 1;
}
else
{
if (fptr != NULL)
if (world_hex.terrain == HOME_DEN)
fprintf (fptr, "HomeDenStarve: %s %d %d %d\n",
work_string,
world_hex.den_lizard_type,
work4,
world_hex.lizard_pop);
else
fprintf (fptr, "DenStarve: %s %d %d %d\n",
work_string,
world_hex.den_lizard_type,
work4,
world_hex.lizard_pop);
world_hex.turns_den_hungry ++;
world_hex.lizard_pop -= work4;
hex_change = 1;
}
}
}
}
else
{
if (world_hex.den_lizard_type == 0)
{
work4 = POP_ADDITION;
world_hex.lizard_pop += work4;
fprintf (fptr, "NomadsJoinDen: %s %d\n",
work_string,
work4);
if (world_hex.lizard_pop > MINIMUM_POP_LEVEL)
{
world_hex.den_lizard_type = random (5) + 1;
fprintf (fptr, "DenSettled: %s %d\n",
work_string,
world_hex.den_lizard_type);
}
hex_change = 1;
}
else
{
if (world_hex.lizard_pop < (work3 * DEN_LIZARD_LEVEL))
{
work4 = lizard_pop_growth (world, world_hex.lizard_pop,
work3 * DEN_LIZARD_LEVEL);
world_hex.lizard_pop += work4;
hex_change = 1;
}
else
{
if (world_hex.lizard_pop > (work3 * DEN_LIZARD_LEVEL) &&
world->turn > 0)
{
work4 = lizard_pop_growth (world, world_hex.lizard_pop,
work3 * DEN_LIZARD_LEVEL);
if (work4 == 0)
work4 = -1;
world_hex.lizard_pop += work4;
if (fptr != NULL)
fprintf (fptr, "DenOverpopulation: %s %d\n",
work_string,
-work4);
hex_change = 1;
}
}
}
}
if (fptr != NULL)
fclose (fptr);
}
if (world_hex.terrain != FERTILE &&
lizards_in_hex (&world_hex) > 0)
{
if (world_hex.turns_hungry < MAX_HUNGER_POINTS && (world->turn > 0))
{
world_hex.turns_hungry ++;
hex_change = 1;
}
}
else
if (world_hex.terrain == FERTILE &&
lizards_in_hex (&world_hex) > 0)
{
world_hex.turns_hungry = 0;
hex_change = 1;
}
return hex_change;
}
/* ---------------------------------------------------------------------- */
int main (int argc, char *argv [])
{
FILE *fptr;
int work,
work2,
hex_change,
header = 0;
hex_t world_hex;
randomize ();
show_title ();
printf ("LIZARDS! World Open. %s Last compiled %s.\n\n",
VER_STRING, __DATE__);
if (argc == 3)
{
data_path = LzCheckDir(argv[1], 0);
game_code = (char*)malloc(strlen(argv[2]) + 1);
strcpy (game_code, argv[2]);
strupr (game_code);
}
else
{
fprintf (stderr, "FATAL ERROR: Turn and Game Number not specified on command line!\n"
" Command Line Format: EXEFILE data_path turn game.\n"
" e.g. WORLOPEN C:\\ 1 A\n");
exit (EXIT_FAILURE);
}
world = (World*)malloc(sizeof(World));
get_world (world);
if (world->num_players == 0)
{
fprintf (stderr, "FATAL ERROR: Game %s has no players.\n", game_code);
exit (EXIT_FAILURE);
}
/* Set up headers for PLAYER message files! */
printf ("Messaging players...");
for (work = 1; work < world->num_players + 1; work ++)
{
open_player_mesg (work, &fptr);
if (header)
fprintf (fptr, "Header: on\n");
else
fprintf(fptr, "Header: off\n");
fprintf (fptr, "ClanID: %s\n", world->player[work].code);
if (world->flags & LZ_SPAWN)
fprintf (fptr, "Spawning: on\n");
else
fprintf (fptr, "Spawning: off\n");
fprintf (fptr, "Phase: world\n");
fclose (fptr);
}
open_player_mesg (0, &fptr);
{
if (header)
fprintf (fptr, "Header: on\n");
else
fprintf(fptr, "Header: off\n");
fprintf (fptr, "Turn: %d\n", world->turn);
fprintf (fptr, "Game: %s\n", game_code);
fprintf (fptr, "DueDate: %s\n", world->due_date);
}
fclose (fptr);
printf (" \nOpening world...");
/* ---------
--
-- process each work hex in turn
--
--------- */
for (work = 0; work < world->x; work ++)
{
for (work2 = 0; work2 < world->y; work2 ++)
{
get_hex (world, work, work2, &world_hex);
hex_change = ProcessHex(world, world_hex);
if (hex_change)
put_hex (world, work, work2, &world_hex);
}
}
printf (" \nUpdating spys...");
/* Update spy turns alone */
for (work = 0; work < world->num_spies; work ++)
{
world->spylist [work]->turns_alone ++;
get_hex (world,
world->spylist [work]->x_hex,
world->spylist [work]->y_hex, &world_hex);
/* Free immobile Spys */
if (world->spylist [work]->mired > 0)
world->spylist [work]->mired -= 1;
/* Clear Spy moved flags */
world->spylist[work]->moved_this_turn = 0;
}
put_world(world);
printf (" \n\nFinished!\n");
return (EXIT_SUCCESS);
}
| C | CL | 16c0b51ed2abd0195a8fef8c4545d0cbb05b7465f2056f09430f15e6c7118970 |
#include "Dahua.h"
#include "BleMaster.h"
#include "chip.h"
#include "delay.h"
#include "wt588d.h"
#include "network.h"
#include "led.h"
#include <string.h>
static unsigned char DahuaFrameBuf[DAHUA_FRAME_MAX_LEN] = {0X00};
static DahuaFrame_t DahuaFrame;
DahuaRet_t DahuaInit(void) {
unsigned char *pos = DahuaFrameBuf;
BleMasterInit();
DahuaFrame.head = pos++;
DahuaFrame.SlaveAddr = pos++;
DahuaFrame.CmdGrp = pos++;
DahuaFrame.CmdCode = pos++;
DahuaFrame.len = pos++;
DahuaFrame.data = pos;
return DAHUA_RET_SUCC;
}
static unsigned char DahuaCalcCheckSum(unsigned char len) {
unsigned char sum = 0;
unsigned short i = 0;
for (i = 0; i < len; i++) {
sum += DahuaFrameBuf[i];
}
return sum;
}
DahuaRet_t DahuaWatiResp(DahuaFrame_t *frame) {
unsigned int timeout = 10000;
unsigned int len = 0;
unsigned char *pos = DahuaFrameBuf;
memset(DahuaFrameBuf, 0x00, sizeof(DAHUA_FRAME_MAX_LEN));
while (timeout--) {
DOG_FEED();
delay_ms(1);
if (BLE_RET_SUCCESS != BleMasterRecv(pos, &len)) {
continue;
}
if (NULL == frame) {
return DAHUA_RET_SUCC;
}
frame->head = pos++;
frame->SlaveAddr = pos++;
frame->CmdGrp = pos++;
frame->CmdCode = pos++;
frame->len = pos++;
frame->data = pos;
frame->chk = frame->data + *(frame->len);
return DAHUA_RET_SUCC;
}
return DAHUA_RET_TIMEOUT;
}
DahuaRet_t DahuaSend(unsigned char CmdGrp, unsigned char CmdCode, unsigned char *data, unsigned char len) {
memset(DahuaFrameBuf, 0x00, DAHUA_FRAME_MAX_LEN);
*(DahuaFrame.head) = 0xA6;
*(DahuaFrame.SlaveAddr) = 0;
*(DahuaFrame.CmdGrp) = CmdGrp;
*(DahuaFrame.CmdCode) = CmdCode;
*(DahuaFrame.len) = len;
if ((0 != len) && (NULL != data)) {
memcpy(DahuaFrame.data, data, len);
}
DahuaFrame.chk = DahuaFrame.data + len;
*(DahuaFrame.chk) = DahuaCalcCheckSum(DAHUA_FRMAE_LEN(DahuaFrame));
BleMasterSend(DahuaFrame.head, DAHUA_FRMAE_LEN(DahuaFrame));
{
unsigned short i = 0;
SYSLOG("Frame Data : ");
for (i = 0; i < DAHUA_FRMAE_LEN(DahuaFrame); i++) {
SYSLOG("%02x ", DahuaFrameBuf[i]);
}
SYSLOG("\r\n");
}
return DAHUA_RET_SUCC;
}
static DahuaRet_t DahuaDealAlarmInfo(DahuaFrame_t frame) {
DahuaAlarmInfo_t AlarmInfo;
if (DAHUA_CMD_UNLOCK_CODE == *(frame.CmdCode)) {
DahuaUnlockInfo_t info = *((DahuaUnlockInfo_t *)(frame.data));
unsigned char UserNum[6] = {0x00};
SYSLOG("type : %d\r\n", info.type);
SYSLOG("ID : %02x%02x%02x%02x\r\n", info.id[0], info.id[1], info.id[2], info.id[3]);
sprintf((char *)UserNum, "%03d", info.id[3]);
SYSLOG("UserNum : %s\r\n", UserNum);
NetWorkSendWarn(NET_WARN_TYPE_OPEN_LOCK, UserNum);
return DAHUA_RET_SUCC;
}
if (DAHUA_CMD_ALARM_CODE != *(frame.CmdCode)) {
return DAHUA_RET_FAIL;
}
AlarmInfo = *((DahuaAlarmInfo_t *)(frame.data));
switch (AlarmInfo.type) {
case DAHUA_ALARM_TYPE_DOORBELL : {
SYSLOG("主人,家里来客人了\r\n");
NetWorkSendWarn(NET_WARN_TYPE_DOORBEEL, NULL);
} break;
case DAHUA_ALARM_TYPE_ILLEGAL_USER : {
SYSLOG("主人,有人非法开锁\r\n");
NetWorkSendWarn(NET_WARN_TYPE_ILLEGAL_LOCK, NULL);
} break;
default : {
} break;
}
return DAHUA_RET_SUCC;
}
static DahuaRet_t DahuaDealBleRspInfo(DahuaFrame_t frame) {
switch (*(frame.CmdCode)) {
case DAHUA_CMD_NEW_DEV_NOTIF : {
SYSLOG("关联响应\r\n");
WT588DStartPlay(WT588D_CONTEX_LOCK_ASSOC_SUCC);
LEDOpen(LED_COLOR_YELLOW, 3);
NetWorkSendWarn(NET_WARN_TYPE_LOCK_ASSOC, NULL);
} break;
default : {
} break;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaRecv(void) {
unsigned int len = 0;
unsigned char *pos = DahuaFrameBuf;
DahuaFrame_t frame;
if (BLE_RET_SUCCESS != BleMasterRecv(pos, &len)) {
return DAHUA_RET_FAIL;
}
frame.head = pos++;
frame.SlaveAddr = pos++;
frame.CmdGrp = pos++;
frame.CmdCode = pos++;
frame.len = pos++;
frame.data = pos;
frame.chk = frame.data + *(frame.len);
switch (*(frame.CmdGrp)) {
case DAHUA_CMD_ALARM_GRP : {
DahuaDealAlarmInfo(frame);
} break;
case DAHUA_BLE_CMD_GRP : {
DahuaDealBleRspInfo(frame);
} break;
default : {
} break;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaGetLinkSta(DahuaLinkSta_t *sta) {
DahuaFrame_t frame;
DahuaSend(DAHUA_BLE_CMD_GRP, DAHUA_CMD_TEST, NULL, 0);
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
if ((DAHUA_BLE_CMD_GRP != *(frame.CmdGrp)) ||
(DAHUA_CMD_TEST_RSP != *(frame.CmdCode))) {
return DAHUA_RET_FAIL;
}
if (NULL != sta) {
*sta = (DahuaLinkSta_t )(frame.data[0]);
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaReset(void) {
DahuaRst_t rst;
rst.time = DAHUA_RST_TIME_DEFAULT;
DahuaSend(DAHUA_BLE_CMD_GRP, DAHUA_CMD_RST, (unsigned char *)&rst, sizeof(DahuaRst_t));
if (DAHUA_RET_SUCC != DahuaWatiResp(NULL)) {
return DAHUA_RET_FAIL;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaGetBindDevice(void) {
DahuaFrame_t frame;
unsigned char i = 0;
unsigned char *pos = NULL;
DahuaSend(DAHUA_BLE_CMD_GRP, DAHUA_CMD_GET_DEV, NULL, 0);
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
if (DAHUA_CMD_GET_DEV_RSP != *(frame.CmdCode)) {
return DAHUA_RET_FAIL;
}
LOG("MAC Number : %d\r\n", frame.data[0]);
pos = frame.data + 1;
for (i = 0; i < frame.data[0]; i++) {
LOG("%d : %02x:%02x:%02x:%02x:%02x:%02x\r\n", i + 1,
pos[0], pos[1], pos[2], pos[3], pos[4], pos[5]);
pos += 6;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaNetAllow(DahuaNetAllow_t allow) {
DahuaFrame_t frame;
DahuaCommonRsp_t rsp;
DahuaSend(DAHUA_BLE_CMD_GRP, DAHUA_CMD_NET_ALLOW, (unsigned char *)&allow, 1);
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
if (DAHUA_CMD_COMMON_RSP != *(frame.CmdCode)) {
return DAHUA_RET_FAIL;
}
rsp = *((DahuaCommonRsp_t *)frame.data);
if ((DAHUA_CMD_NET_ALLOW != rsp.cmd) ||
(DAHUA_COMMON_RSP_FAIL == rsp.rsp)) {
return DAHUA_RET_FAIL;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaNewDevNotif(DahuaNewDev_t dev) {
DahuaFrame_t frame;
DahuaCommonRsp_t rsp;
DahuaSend(DAHUA_BLE_CMD_GRP, DAHUA_CMD_NEW_DEV_NOTIF, (unsigned char *)&dev, sizeof(DahuaNewDev_t));
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
if (DAHUA_CMD_COMMON_RSP != *(frame.CmdCode)) {
return DAHUA_RET_FAIL;
}
rsp = *((DahuaCommonRsp_t *)frame.data);
if ((DAHUA_CMD_NEW_DEV_NOTIF != rsp.cmd) ||
(DAHUA_COMMON_RSP_FAIL == rsp.rsp)) {
return DAHUA_RET_FAIL;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaRegRequest(DahuaRegister_t reg, DahuaBindSta_t *sta) {
DahuaFrame_t frame;
DahuaSend(DAHUA_BLE_CMD_GRP, DAHUA_CMD_REGISTER, (unsigned char *)®, sizeof(DahuaRegister_t));
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
if (DAHUA_CMD_REGISTER_RSP != *(frame.CmdCode)) {
return DAHUA_RET_FAIL;
}
if (NULL != sta) {
*sta = (DahuaBindSta_t)(frame.data[0]);
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaRegStaNotif(DahuaRegNotif_t *notif) {
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaSetSecretKey(DahuaSecretKey_t key) {
DahuaFrame_t frame;
DahuaCommonRsp_t rsp;
DahuaSend(DAHUA_BLE_CMD_GRP, DAHUA_CMD_SET_SECRETKEY, (unsigned char *)&key, sizeof(DahuaSecretKey_t));
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
if (DAHUA_CMD_COMMON_RSP != *(frame.CmdCode)) {
return DAHUA_RET_FAIL;
}
rsp = *((DahuaCommonRsp_t *)frame.data);
if ((DAHUA_CMD_SET_SECRETKEY != rsp.cmd) ||
(DAHUA_COMMON_RSP_FAIL == rsp.rsp)) {
return DAHUA_RET_FAIL;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaSetMatchPwd(int pwd) {
DahuaFrame_t frame;
DahuaCommonRsp_t rsp;
unsigned char data[4] = {0X00};
unsigned char i = 0;
/* big endian */
for (i = 4; i > 0; i--) {
data[i-1] = (unsigned char)(pwd & 0x000000FF);
pwd >>= 8;
}
DahuaSend(DAHUA_BLE_CMD_GRP, DAHUA_CMD_SET_MATCH_PWD, data, 4);
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
if (DAHUA_CMD_COMMON_RSP != *(frame.CmdCode)) {
return DAHUA_RET_FAIL;
}
rsp = *((DahuaCommonRsp_t *)frame.data);
if ((DAHUA_CMD_SET_MATCH_PWD != rsp.cmd) ||
(DAHUA_COMMON_RSP_FAIL == rsp.rsp)) {
return DAHUA_RET_FAIL;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaUnlock(DahuaUnlock_t unlock, DahuaUnlockRsp_t *rsp) {
DahuaFrame_t frame;
DahuaSend(0x06, DAHUA_CMD_UNLOCK, (unsigned char *)&unlock, sizeof(DahuaUnlock_t));
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
if (DAHUA_CMD_UNLOCK_RSP != *(frame.CmdCode)) {
return DAHUA_RET_FAIL;
}
if (NULL != rsp) {
*rsp = *((DahuaUnlockRsp_t *)(frame.data));
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaLock(DahuaLock_t lock, DahuaLockRsp_t *rsp) {
DahuaFrame_t frame;
DahuaCommonAck_t ack;
DahuaSend(0x10, DAHUA_CMD_LOCK, (unsigned char *)&lock, sizeof(DahuaLock_t));
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
ack.cmd = DAHUA_CMD_LOCK_RSP;
if ((0x01 != *(frame.CmdGrp)) ||
(DAHUA_CMD_LOCK_RSP != *(frame.CmdCode))) {
ack.ack = DAHUA_COMMON_ACK_FAIL;
DahuaSend(0x20, DAHUA_CMD_ACK, (unsigned char *)&ack, sizeof(DahuaCommonAck_t));
return DAHUA_RET_FAIL;
}
if (NULL != rsp) {
*rsp = *((DahuaLockRsp_t *)(frame.data));
}
ack.ack = DAHUA_COMMON_ACK_SUCC;
DahuaSend(0x20, DAHUA_CMD_ACK, (unsigned char *)&ack, sizeof(DahuaCommonAck_t));
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaRecordQuery(DahuaQueryType_t type) {
DahuaFrame_t frame;
DahuaSend(0x10, DAHUA_CMD_QUERY, (unsigned char *)&type, sizeof(DahuaQueryType_t));
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaAlarmControl(DahuaAlarmCtl_t ctl) {
DahuaFrame_t frame;
DahuaSend(0x10, DAHUA_CMD_ALARM_CTL, (unsigned char *)&ctl, sizeof(DahuaAlarmCtl_t));
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaUnlockRecordQuery(DahuaUnlockQuery_t query) {
DahuaFrame_t frame;
DahuaSend(0x06, DAHUA_CMD_UNLOCK_QUERY, (unsigned char *)&query, sizeof(DahuaUnlockQuery_t));
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaGetVersion(void) {
DahuaSend(0x06, DAHUA_CMD_GET_VERSION, NULL, 0);
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaDeleteDevice(DahuaDelete_t del) {
DahuaFrame_t frame;
unsigned char len = sizeof(DahuaDelete_t);
if (DAHUA_DELETE_TYPE_ALL == del.type) {
len -= DAHUA_MAC_LEN;
}
DahuaSend(DAHUA_BLE_CMD_GRP, DAHUA_CMD_DELETE_DEV, (unsigned char *)&del, len);
if (DAHUA_RET_SUCC != DahuaWatiResp(&frame)) {
return DAHUA_RET_FAIL;
}
if ((DAHUA_BLE_CMD_GRP != *(frame.CmdGrp)) ||
(DAHUA_CMD_COMMON_RSP != *(frame.CmdCode))) {
return DAHUA_RET_FAIL;
}
return DAHUA_RET_SUCC;
}
DahuaRet_t DahuaLockAssoc(void) {
DahuaDelete_t del = {DAHUA_DELETE_TYPE_ALL};
if (DAHUA_RET_SUCC != DahuaDeleteDevice(del)) {
return DAHUA_RET_FAIL;
}
if (DAHUA_RET_SUCC != DahuaReset()) {
return DAHUA_RET_FAIL;
}
delay_ms(1000);
if (DAHUA_RET_SUCC != DahuaNetAllow(DAHUA_NET_ALLOW_START)) {
return DAHUA_RET_FAIL;
}
return DAHUA_RET_SUCC;
}
| C | CL | cd6125c7cc5a1d2fdd899b0fb57368bd992ff4d3731a0bef80d382ec28b055e8 |
// C:\diabpsx\PSXSRC\PRIMPOOL.H
#include "types.h"
// address: 0x801335C0
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_FT4(struct POLY_FT4 **Prim) {
}
// address: 0x801575FC
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP7LINE_F2(struct LINE_F2 **Prim) {
}
// address: 0x800836AC
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_GT3(struct POLY_GT3 **Prim) {
}
// address: 0x80083728
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_GT4(struct POLY_GT4 **Prim) {
}
// address: 0x800837A4
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_FT4_addr_800837A4(struct POLY_FT4 **Prim) {
}
// address: 0x8008DF4C
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_FT4_addr_8008DF4C(struct POLY_FT4 **Prim) {
}
// address: 0x8008E010
// size: 0x28
// line start: 84
// line end: 89
struct POLY_FT4 *PRIM_GetCopy__FP8POLY_FT4(struct POLY_FT4 *Prim) {
// address: 0xFFFFFFF0
// size: 0x28
auto struct POLY_FT4 *RetPrim;
}
// address: 0x8008E094
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_GT4_addr_8008E094(struct POLY_GT4 **Prim) {
}
// address: 0x8008E110
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP7LINE_F2_addr_8008E110(struct LINE_F2 **Prim) {
}
// address: 0x8008E18C
// line start: 75
// line end: 80
void PRIM_CopyPrim__FP8POLY_FT4T0(struct POLY_FT4 *Dest, struct POLY_FT4 *Source) {
// register: 4
register unsigned long *Dest32;
// register: 5
register unsigned long *Source32;
{
// register: 3
register unsigned int f;
}
}
// address: 0x8008F6AC
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_FT4_addr_8008F6AC(struct POLY_FT4 **Prim) {
}
// address: 0x8008F728
// size: 0x28
// line start: 84
// line end: 89
struct POLY_FT4 *PRIM_GetCopy__FP8POLY_FT4_addr_8008F728(struct POLY_FT4 *Prim) {
// address: 0xFFFFFFF0
// size: 0x28
auto struct POLY_FT4 *RetPrim;
}
// address: 0x8008F764
// line start: 75
// line end: 80
void PRIM_CopyPrim__FP8POLY_FT4T0_addr_8008F764(struct POLY_FT4 *Dest, struct POLY_FT4 *Source) {
// register: 4
register unsigned long *Dest32;
// register: 5
register unsigned long *Source32;
{
// register: 3
register unsigned int f;
}
}
// address: 0x80096F18
// size: 0x28
// line start: 84
// line end: 89
struct POLY_FT4 *PRIM_GetCopy__FP8POLY_FT4_addr_80096F18(struct POLY_FT4 *Prim) {
// address: 0xFFFFFFF0
// size: 0x28
auto struct POLY_FT4 *RetPrim;
}
// address: 0x80096F54
// line start: 75
// line end: 80
void PRIM_CopyPrim__FP8POLY_FT4T0_addr_80096F54(struct POLY_FT4 *Dest, struct POLY_FT4 *Source) {
// register: 4
register unsigned long *Dest32;
// register: 5
register unsigned long *Source32;
{
// register: 3
register unsigned int f;
}
}
// address: 0x80096F7C
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_FT4_addr_80096F7C(struct POLY_FT4 **Prim) {
}
// address: 0x800992F0
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP7POLY_G4(struct POLY_G4 **Prim) {
}
// address: 0x8009936C
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP7POLY_F4(struct POLY_F4 **Prim) {
}
// address: 0x800993E8
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_FT4_addr_800993E8(struct POLY_FT4 **Prim) {
}
// address: 0x8009D524
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP7POLY_G4_addr_8009D524(struct POLY_G4 **Prim) {
}
// address: 0x800A1E50
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP7POLY_G4_addr_800A1E50(struct POLY_G4 **Prim) {
}
// address: 0x800A3744
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_FT4_addr_800A3744(struct POLY_FT4 **Prim) {
}
// address: 0x80063134
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_FT4_addr_80063134(struct POLY_FT4 **Prim) {
}
// address: 0x80077BAC
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_FT4_addr_80077BAC(struct POLY_FT4 **Prim) {
}
// address: 0x80079D6C
// size: 0x28
// line start: 84
// line end: 89
struct POLY_FT4 *PRIM_GetCopy__FP8POLY_FT4_addr_80079D6C(struct POLY_FT4 *Prim) {
// address: 0xFFFFFFF0
// size: 0x28
auto struct POLY_FT4 *RetPrim;
}
// address: 0x80079DA8
// line start: 75
// line end: 80
void PRIM_CopyPrim__FP8POLY_FT4T0_addr_80079DA8(struct POLY_FT4 *Dest, struct POLY_FT4 *Source) {
// register: 4
register unsigned long *Dest32;
// register: 5
register unsigned long *Source32;
{
// register: 3
register unsigned int f;
}
}
// address: 0x80079DD0
// line start: 65
// line end: 71
void PRIM_GetPrim__FPP8POLY_FT4_addr_80079DD0(struct POLY_FT4 **Prim) {
}
| C | CL | d9ed654fd068a7c6c7d6081931c9ef7c3952ff3888714a260e7e4b09cb14d079 |
#include <stdio.h>
#include <memory.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <wait.h>
//defines
#define INPUT_SIZE 1000
#define JOBS_NUM 1000
#define HOME "HOME"
#define SUCCESS 1
#define FAIL -1
#define TRUE 1
#define FALSE 0
#define ERROR "Error in system call"
//declarations
int callExecv(char **args, int isBackground);
int cdImplementation(char *args[],char lastCdDir[INPUT_SIZE]);
void printJobs(int pids[], char jobs[JOBS_NUM][INPUT_SIZE], int j);
void makeArgs(char *args[INPUT_SIZE], char input[INPUT_SIZE], int* isBackground);
int changeSpecipicCdDir(char *dir,char lastCdDir[INPUT_SIZE], int isCdMinus);
int changeCd2Home(char lastCdDir[INPUT_SIZE]);
/**
* main function.
* runs the program
* @return 0
*/
int main() {
//allocate memory for jobs arrays
char jobs[JOBS_NUM][INPUT_SIZE];
int pids[JOBS_NUM];
int j =0;
char lastCdDir[INPUT_SIZE] ="";
//while loop runs the shell
while (TRUE) {
printf("prompt>");
int isBackground = FALSE;
//allocate memory for input
char input[INPUT_SIZE];
char copyInput[INPUT_SIZE];
//scan input from user
fgets(input, INPUT_SIZE, stdin);
//remove '/n'
input[strlen(input) - 1] = '\0';
//copy input
strcpy(copyInput,input);
//operate the action
if (strcmp(input, "jobs")==0) {
printJobs(pids,jobs,j);
} else if (strcmp(input, "exit")==0) {
printf("%d \n", getpid());
exit(0);
} else {
//allocate memory for args array
char *args[INPUT_SIZE];
makeArgs(args, input, &isBackground);
if (args[0]==NULL){
continue;
}
if (strcmp(args[0],"cd")==0) {
printf("%d \n", getpid());
cdImplementation(args,lastCdDir);
} else {
//calling execv
int pid = callExecv(args, isBackground);
//update pids array
pids[j] = pid;
strcpy(jobs[j], copyInput);
j++;
}
}
}
return (0);
}
/**
* callExecv function.
* @param args - array for execvp function
* @param isBackground - tells if parent need to wait to son
* @return pid of son
*/
int callExecv(char **args, int isBackground) {
int stat, retCode;
pid_t pid;
pid = fork();
if (pid == 0) { // son
retCode = execvp(args[0], &args[0]);
if (retCode == FAIL) {
fprintf(stderr, ERROR);
printf("\n");
exit(FAIL);
}
} else { //father prints pid of son
printf("%d \n", pid);
if (!isBackground) {
waitpid(pid,NULL,0); // stat can tell what happened
}
}
return pid;
}
/**
* cdImplementation function.
* @param args - input arguments
* @return success or failure
*/
int cdImplementation(char *args[],char lastCdDir[INPUT_SIZE]){
if (args[1] ==NULL){
return changeCd2Home(lastCdDir);
} else {
int i =0;
while (args[i]!=NULL) {
i++;
}
if (i==2 && strcmp(args[1],"-")==0){
return changeSpecipicCdDir(lastCdDir,lastCdDir,TRUE);
} else if (i==2&& strcmp(args[1],"~")==0) {
return changeCd2Home(lastCdDir);
} else {
return changeSpecipicCdDir(args[1],lastCdDir,FALSE);
}
}
}
/**
* changeSpecipicCdDir function.
* @param dir - cd dir
* @param lastCdDir - prev cd dir
* @param isCdMinus - indicates if command is "cd -"
* @return FAIL or SUCCESS
*/
int changeSpecipicCdDir(char *dir,char lastCdDir[INPUT_SIZE], int isCdMinus) {
char cwd[INPUT_SIZE];
getcwd(cwd,INPUT_SIZE);
if (chdir(dir) == FAIL) {
fprintf(stderr, ERROR);
printf("\n");
return FAIL;
} else {
if(isCdMinus==TRUE){
printf("%s\n", dir);
}
strcpy(lastCdDir,cwd);
return SUCCESS;
}
}
/**
* changeCd2Home function.
* @param lastCdDir - prev cd dir
* @return FAIL or SUCCESS
*/
int changeCd2Home(char lastCdDir[INPUT_SIZE]){
char cwd[INPUT_SIZE];
getcwd(cwd,INPUT_SIZE);
if(chdir(getenv(HOME))==FAIL) {
fprintf(stderr, ERROR);
printf("\n");
return FAIL;
} else {
strcpy(lastCdDir,cwd);
return SUCCESS;
}
}
/**
* printJobs function.
* @param pids - array of jobs pids
* @param jobs - array of jobs commands
* @param j - len of jobs array
*/
void printJobs(int pids[], char jobs[JOBS_NUM][INPUT_SIZE], int j){
int flag =FALSE;
int i;
for (i=0; i<j; i++) {
pid_t returnPid = waitpid(pids[i], NULL, WNOHANG);
if (returnPid ==0) {
flag=TRUE;
printf("%d ", pids[i]);
int len = strlen(jobs[i]);
int k;
for (k=0; k<len;k++){
if (!((k==len-1)&&jobs[i][k]=='&')){
printf("%c", jobs[i][k]);
}
}
}
}
if (flag) {
printf("\n");
}
}
/**
* makeArgs function.
* @param args - array for execvp function
* @param input - user's input
* @param isBackground - tells if parent need to wait to son
*/
void makeArgs(char *args[INPUT_SIZE], char input[INPUT_SIZE], int* isBackground){
const char s[2] = " ";
char *token;
//get the first token
int i = 0;
token = strtok(input, s);
args[i]= token;
//walk through other tokens
while (token != NULL) {
token = strtok(NULL, s);
if (token != NULL && strcmp(token, "&") != 0) {
i++;
args[i]= token;
} else if (token != NULL && strcmp(token, "&") == 0) {
*isBackground = TRUE;
}
}
i++;
args[i] = NULL;
} | C | CL | 24ae13cdeffa2d09a53e56889f1a1a1770e505585f9cced1c4dbc6dbc15e2bb1 |
////////////////////////////////////////////////////////////////////////////////
// _______ ____________________________________ //
// \\ . \ _________/ . . . . . . . . . . . . . . . . / //
// \\ . \ ___/ . . . . . ______________________________/ //
// \\ . \ __/. . . _________/ / // . __________/ //
// \\ . \_// ___/ . _____ / // . /______ //
// \\ . \/ _/ // . / \\ | \\ . \ //
// \\ . / || . | || | \\______ \ //
// \\ . / || . \____// | _________// / //
// \\ . / // . / // . . . . / //
// \\____/ //_______________/ //______________/ //
// //
////////////////////////////////////////////////////////////////////////////////
// This is free and unencumbered software released into the public domain. //
// //
// Anyone is free to copy, modify, publish, use, compile, sell, or //
// distribute this software, either in source code form or as a compiled //
// binary, for any purpose, commercial or non-commercial, and by any //
// means. //
// //
// In jurisdictions that recognize copyright laws, the author or authors //
// of this software dedicate any and all copyright interest in the //
// software to the public domain. We make this dedication for the benefit //
// of the public at large and to the detriment of our heirs and //
// successors. We intend this dedication to be an overt act of //
// relinquishment in perpetuity of all present and future rights to this //
// software under copyright law. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, //
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. //
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR //
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, //
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR //
// OTHER DEALINGS IN THE SOFTWARE. //
// //
// For more information, please refer to <https://unlicense.org> //
////////////////////////////////////////////////////////////////////////////////
// VOS : Virtual Operating System //
// Images/Embedded/ProgressBar.h : ProgressBar embedded image //
////////////////////////////////////////////////////////////////////////////////
#ifndef VOS_IMAGES_EMBEDDED_PROGRESSBAR_HEADER
#define VOS_IMAGES_EMBEDDED_PROGRESSBAR_HEADER
#include "../../System/System.h"
////////////////////////////////////////////////////////////////////////////
// ProgressBar embedded image //
////////////////////////////////////////////////////////////////////////////
const unsigned int ProgressBarImageWidth = 32;
const unsigned int ProgressBarImageHeight = 64;
const unsigned char ProgressBarImage[32 * 64 * 4] =
{
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x1B, 0x1B, 0x1B, 0x25, 0x19, 0x19, 0x19, 0xAD,
0x1A, 0x1A, 0x1A, 0xF1, 0x1B, 0x1B, 0x1B, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF,
0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF,
0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF,
0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF,
0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF,
0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF,
0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF,
0x1C, 0x1C, 0x1C, 0xFF, 0x1D, 0x1D, 0x1D, 0xFF, 0x1E, 0x1E, 0x1E, 0xF1,
0x22, 0x22, 0x22, 0xAD, 0x27, 0x27, 0x27, 0x25, 0x2D, 0x2D, 0x2D, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x1E, 0x1E, 0x1E, 0x27,
0x1C, 0x1C, 0x1C, 0xEF, 0x21, 0x21, 0x21, 0xFF, 0x27, 0x27, 0x27, 0xFF,
0x2B, 0x2B, 0x2B, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF,
0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF,
0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF,
0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF,
0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF,
0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF,
0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF, 0x2C, 0x2C, 0x2C, 0xFF,
0x2C, 0x2C, 0x2C, 0xFF, 0x2B, 0x2B, 0x2B, 0xFF, 0x2A, 0x2A, 0x2A, 0xFF,
0x2B, 0x2B, 0x2B, 0xEF, 0x2F, 0x2F, 0x2F, 0x27, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x1F, 0x1F, 0x1F, 0xAD, 0x25, 0x25, 0x25, 0xFF,
0x2E, 0x2E, 0x2E, 0xFF, 0x33, 0x33, 0x33, 0xFF, 0x35, 0x35, 0x35, 0xFF,
0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF,
0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF,
0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF,
0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF,
0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF,
0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF,
0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF, 0x35, 0x35, 0x35, 0xFF,
0x34, 0x34, 0x34, 0xFF, 0x33, 0x33, 0x33, 0xFF, 0x34, 0x34, 0x34, 0xFF,
0x38, 0x38, 0x38, 0xAD, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x24, 0x24, 0x24, 0xF1, 0x2E, 0x2E, 0x2E, 0xFF, 0x35, 0x35, 0x35, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x4D, 0x4D, 0x4D, 0xF3,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x28, 0x28, 0x28, 0xFF,
0x33, 0x33, 0x33, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x45, 0x45, 0x45, 0xFF, 0x59, 0x59, 0x59, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x2C, 0x2C, 0x2C, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF,
0x5E, 0x5E, 0x5E, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x2E, 0x2E, 0x2E, 0xFF, 0x3A, 0x3A, 0x3A, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x62, 0x62, 0x62, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x2F, 0x2F, 0x2F, 0xFF,
0x3B, 0x3B, 0x3B, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF,
0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF,
0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF,
0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF,
0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF,
0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF,
0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF,
0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF,
0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x41, 0x41, 0x41, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x63, 0x63, 0x63, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x31, 0x31, 0x31, 0xFF, 0x3E, 0x3E, 0x3E, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x52, 0x52, 0x52, 0xFF,
0x66, 0x66, 0x66, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x34, 0x34, 0x34, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x55, 0x55, 0x55, 0xFF, 0x68, 0x68, 0x68, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x35, 0x35, 0x35, 0xFF,
0x43, 0x43, 0x43, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x57, 0x57, 0x57, 0xFF, 0x6A, 0x6A, 0x6A, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x36, 0x36, 0x36, 0xFF, 0x45, 0x45, 0x45, 0xFF,
0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF,
0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF,
0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF,
0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF,
0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF,
0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF,
0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF,
0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF,
0x4B, 0x4B, 0x4B, 0xFF, 0x4B, 0x4B, 0x4B, 0xFF, 0x58, 0x58, 0x58, 0xFF,
0x6B, 0x6B, 0x6B, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x38, 0x38, 0x38, 0xFF, 0x46, 0x46, 0x46, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x5A, 0x5A, 0x5A, 0xFF, 0x6D, 0x6D, 0x6D, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x39, 0x39, 0x39, 0xFF,
0x48, 0x48, 0x48, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x5C, 0x5C, 0x5C, 0xFF, 0x6F, 0x6F, 0x6F, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x3A, 0x3A, 0x3A, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x5D, 0x5D, 0x5D, 0xFF,
0x70, 0x70, 0x70, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x3A, 0x3A, 0x3A, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x5D, 0x5D, 0x5D, 0xFF, 0x70, 0x70, 0x70, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x3A, 0x3A, 0x3A, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x5D, 0x5D, 0x5D, 0xFF, 0x70, 0x70, 0x70, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x39, 0x39, 0x39, 0xFF, 0x48, 0x48, 0x48, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, 0x5C, 0x5C, 0x5C, 0xFF,
0x6F, 0x6F, 0x6F, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x38, 0x38, 0x38, 0xFF, 0x46, 0x46, 0x46, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF,
0x4D, 0x4D, 0x4D, 0xFF, 0x5A, 0x5A, 0x5A, 0xFF, 0x6D, 0x6D, 0x6D, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x37, 0x37, 0x37, 0xFF,
0x45, 0x45, 0x45, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF,
0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF,
0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF,
0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF,
0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF,
0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF,
0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF,
0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF,
0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF, 0x4C, 0x4C, 0x4C, 0xFF,
0x59, 0x59, 0x59, 0xFF, 0x6C, 0x6C, 0x6C, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x35, 0x35, 0x35, 0xFF, 0x43, 0x43, 0x43, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF,
0x49, 0x49, 0x49, 0xFF, 0x49, 0x49, 0x49, 0xFF, 0x57, 0x57, 0x57, 0xFF,
0x6A, 0x6A, 0x6A, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x34, 0x34, 0x34, 0xFF, 0x41, 0x41, 0x41, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF, 0x47, 0x47, 0x47, 0xFF,
0x47, 0x47, 0x47, 0xFF, 0x55, 0x55, 0x55, 0xFF, 0x68, 0x68, 0x68, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x31, 0x31, 0x31, 0xFF,
0x3E, 0x3E, 0x3E, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF, 0x44, 0x44, 0x44, 0xFF,
0x52, 0x52, 0x52, 0xFF, 0x66, 0x66, 0x66, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x30, 0x30, 0x30, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF,
0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF,
0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF,
0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF,
0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF,
0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF,
0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF,
0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF,
0x42, 0x42, 0x42, 0xFF, 0x42, 0x42, 0x42, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x64, 0x64, 0x64, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x2E, 0x2E, 0x2E, 0xFF, 0x3A, 0x3A, 0x3A, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF,
0x3F, 0x3F, 0x3F, 0xFF, 0x4D, 0x4D, 0x4D, 0xFF, 0x62, 0x62, 0x62, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x2D, 0x2D, 0x2D, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x3D, 0x3D, 0x3D, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3C, 0x3C, 0x3C, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF, 0x3E, 0x3E, 0x3E, 0xFF,
0x4E, 0x4E, 0x4E, 0xFF, 0x62, 0x62, 0x62, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0x2D, 0x2D, 0x2D, 0xF1, 0x35, 0x35, 0x35, 0xFF,
0x3A, 0x3A, 0x3A, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x39, 0x39, 0x39, 0xFF,
0x39, 0x39, 0x39, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, 0x57, 0x57, 0x57, 0xFF,
0x69, 0x69, 0x69, 0xF3, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x31, 0x31, 0x31, 0xAD, 0x36, 0x36, 0x36, 0xFF, 0x3C, 0x3C, 0x3C, 0xFF,
0x3A, 0x3A, 0x3A, 0xFF, 0x38, 0x38, 0x38, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF, 0x37, 0x37, 0x37, 0xFF,
0x37, 0x37, 0x37, 0xFF, 0x39, 0x39, 0x39, 0xFF, 0x3E, 0x3E, 0x3E, 0xFF,
0x4F, 0x4F, 0x4F, 0xFF, 0x6B, 0x6B, 0x6B, 0xFF, 0x76, 0x76, 0x76, 0xAD,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x35, 0x35, 0x35, 0x28,
0x43, 0x43, 0x43, 0xEF, 0x50, 0x50, 0x50, 0xFF, 0x52, 0x52, 0x52, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF, 0x50, 0x50, 0x50, 0xFF,
0x54, 0x54, 0x54, 0xFF, 0x5E, 0x5E, 0x5E, 0xFF, 0x71, 0x71, 0x71, 0xFF,
0x80, 0x80, 0x80, 0xEF, 0x7A, 0x7A, 0x7A, 0x28, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x4E, 0x4E, 0x4E, 0x27,
0x63, 0x63, 0x63, 0xAD, 0x71, 0x71, 0x71, 0xF2, 0x78, 0x78, 0x78, 0xFF,
0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF,
0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF,
0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF,
0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF,
0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF,
0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF, 0x79, 0x79, 0x79, 0xFF,
0x79, 0x79, 0x79, 0xFF, 0x7A, 0x7A, 0x7A, 0xFF, 0x7C, 0x7C, 0x7C, 0xFF,
0x81, 0x81, 0x81, 0xF2, 0x85, 0x85, 0x85, 0xAD, 0x80, 0x80, 0x80, 0x27,
0x69, 0x69, 0x69, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xD9, 0xD9, 0xD9, 0x25,
0xDA, 0xDA, 0xDA, 0xAD, 0xD5, 0xD5, 0xD5, 0xF1, 0xD3, 0xD3, 0xD3, 0xFF,
0xD2, 0xD2, 0xD2, 0xFF, 0xD2, 0xD2, 0xD2, 0xFF, 0xD2, 0xD2, 0xD2, 0xFF,
0xD2, 0xD2, 0xD2, 0xFF, 0xD2, 0xD2, 0xD2, 0xFF, 0xD2, 0xD2, 0xD2, 0xFF,
0xD2, 0xD2, 0xD2, 0xFF, 0xD2, 0xD2, 0xD2, 0xFF, 0xD2, 0xD2, 0xD2, 0xFF,
0xD2, 0xD2, 0xD2, 0xFF, 0xD2, 0xD2, 0xD2, 0xFF, 0xD2, 0xD2, 0xD2, 0xFF,
0xD2, 0xD2, 0xD2, 0xFF, 0xD2, 0xD2, 0xD2, 0xFF, 0xD2, 0xD2, 0xD2, 0xFF,
0xD2, 0xD2, 0xD2, 0xFF, 0xD1, 0xD1, 0xD1, 0xFF, 0xD1, 0xD1, 0xD1, 0xF1,
0xD2, 0xD2, 0xD2, 0xAD, 0xCE, 0xCE, 0xCE, 0x25, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xD7, 0xD7, 0xD7, 0x27, 0xD7, 0xD7, 0xD7, 0xEF, 0xD1, 0xD1, 0xD1, 0xFF,
0xCB, 0xCB, 0xCB, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC8, 0xC8, 0xC8, 0xEF, 0xC7, 0xC7, 0xC7, 0x27, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xD7, 0xD7, 0xD7, 0xAD,
0xCF, 0xCF, 0xCF, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF,
0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF,
0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF,
0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF,
0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF,
0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBB, 0xBB, 0xBB, 0xAD, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xD2, 0xD2, 0xD2, 0xF1, 0xC9, 0xC9, 0xC9, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF, 0xB9, 0xB9, 0xB9, 0xFF,
0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF,
0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF,
0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF,
0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF,
0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF,
0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, 0xB9, 0xB9, 0xB9, 0xFF,
0xB6, 0xB6, 0xB6, 0xFF, 0xB0, 0xB0, 0xB0, 0xFF, 0xAC, 0xAC, 0xAC, 0xF3,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xD0, 0xD0, 0xD0, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBB, 0xBB, 0xBB, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xB4, 0xB4, 0xB4, 0xFF,
0xAC, 0xAC, 0xAC, 0xFF, 0xA5, 0xA5, 0xA5, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xD0, 0xD0, 0xD0, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xBF, 0xBF, 0xBF, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, 0xAA, 0xAA, 0xAA, 0xFF,
0xA2, 0xA2, 0xA2, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xD1, 0xD1, 0xD1, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC1, 0xC1, 0xC1, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xB7, 0xB7, 0xB7, 0xFF, 0xAB, 0xAB, 0xAB, 0xFF, 0xA2, 0xA2, 0xA2, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xD2, 0xD2, 0xD2, 0xFF, 0xCA, 0xCA, 0xCA, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xB9, 0xB9, 0xB9, 0xFF,
0xAD, 0xAD, 0xAD, 0xFF, 0xA3, 0xA3, 0xA3, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xD3, 0xD3, 0xD3, 0xFF,
0xCB, 0xCB, 0xCB, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF, 0xAF, 0xAF, 0xAF, 0xFF,
0xA5, 0xA5, 0xA5, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xD5, 0xD5, 0xD5, 0xFF, 0xCD, 0xCD, 0xCD, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xBD, 0xBD, 0xBD, 0xFF, 0xB0, 0xB0, 0xB0, 0xFF, 0xA6, 0xA6, 0xA6, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xD6, 0xD6, 0xD6, 0xFF, 0xCF, 0xCF, 0xCF, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xBF, 0xBF, 0xBF, 0xFF,
0xB2, 0xB2, 0xB2, 0xFF, 0xA7, 0xA7, 0xA7, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xD7, 0xD7, 0xD7, 0xFF,
0xCF, 0xCF, 0xCF, 0xFF, 0xC9, 0xC9, 0xC9, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xB2, 0xB2, 0xB2, 0xFF,
0xA8, 0xA8, 0xA8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xD8, 0xD8, 0xD8, 0xFF, 0xD0, 0xD0, 0xD0, 0xFF,
0xCA, 0xCA, 0xCA, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC1, 0xC1, 0xC1, 0xFF, 0xB3, 0xB3, 0xB3, 0xFF, 0xA9, 0xA9, 0xA9, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xD8, 0xD8, 0xD8, 0xFF, 0xD0, 0xD0, 0xD0, 0xFF, 0xCA, 0xCA, 0xCA, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF,
0xB3, 0xB3, 0xB3, 0xFF, 0xA9, 0xA9, 0xA9, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xD8, 0xD8, 0xD8, 0xFF,
0xD0, 0xD0, 0xD0, 0xFF, 0xCA, 0xCA, 0xCA, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF, 0xB3, 0xB3, 0xB3, 0xFF,
0xA9, 0xA9, 0xA9, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xD7, 0xD7, 0xD7, 0xFF, 0xCF, 0xCF, 0xCF, 0xFF,
0xC9, 0xC9, 0xC9, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF, 0xC7, 0xC7, 0xC7, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xB2, 0xB2, 0xB2, 0xFF, 0xA8, 0xA8, 0xA8, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xD6, 0xD6, 0xD6, 0xFF, 0xCF, 0xCF, 0xCF, 0xFF, 0xC8, 0xC8, 0xC8, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF,
0xC6, 0xC6, 0xC6, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xBF, 0xBF, 0xBF, 0xFF,
0xB2, 0xB2, 0xB2, 0xFF, 0xA7, 0xA7, 0xA7, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xD5, 0xD5, 0xD5, 0xFF,
0xCD, 0xCD, 0xCD, 0xFF, 0xC6, 0xC6, 0xC6, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xBD, 0xBD, 0xBD, 0xFF, 0xB0, 0xB0, 0xB0, 0xFF,
0xA6, 0xA6, 0xA6, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xD3, 0xD3, 0xD3, 0xFF, 0xCB, 0xCB, 0xCB, 0xFF,
0xC4, 0xC4, 0xC4, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xBB, 0xBB, 0xBB, 0xFF, 0xAF, 0xAF, 0xAF, 0xFF, 0xA5, 0xA5, 0xA5, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xD2, 0xD2, 0xD2, 0xFF, 0xCA, 0xCA, 0xCA, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF,
0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xB9, 0xB9, 0xB9, 0xFF,
0xAD, 0xAD, 0xAD, 0xFF, 0xA3, 0xA3, 0xA3, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xD0, 0xD0, 0xD0, 0xFF,
0xC8, 0xC8, 0xC8, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xB7, 0xB7, 0xB7, 0xFF, 0xAA, 0xAA, 0xAA, 0xFF,
0xA1, 0xA1, 0xA1, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xCF, 0xCF, 0xCF, 0xFF, 0xC5, 0xC5, 0xC5, 0xFF,
0xBE, 0xBE, 0xBE, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xBC, 0xBC, 0xBC, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF, 0xBB, 0xBB, 0xBB, 0xFF,
0xB2, 0xB2, 0xB2, 0xFF, 0xA5, 0xA5, 0xA5, 0xFF, 0x9D, 0x9D, 0x9D, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xCC, 0xCC, 0xCC, 0xF1, 0xC2, 0xC2, 0xC2, 0xFF, 0xBC, 0xBC, 0xBC, 0xFF,
0xB9, 0xB9, 0xB9, 0xFF, 0xB9, 0xB9, 0xB9, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF, 0xBA, 0xBA, 0xBA, 0xFF,
0xB9, 0xB9, 0xB9, 0xFF, 0xB4, 0xB4, 0xB4, 0xFF, 0xA9, 0xA9, 0xA9, 0xFF,
0x9B, 0x9B, 0x9B, 0xFF, 0x97, 0x97, 0x97, 0xF3, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xC9, 0xC9, 0xC9, 0xAD,
0xBA, 0xBA, 0xBA, 0xFF, 0xAF, 0xAF, 0xAF, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF,
0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF,
0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF,
0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF,
0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF,
0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF,
0xAC, 0xAC, 0xAC, 0xFF, 0xAC, 0xAC, 0xAC, 0xFF, 0xAA, 0xAA, 0xAA, 0xFF,
0xA3, 0xA3, 0xA3, 0xFF, 0x97, 0x97, 0x97, 0xFF, 0x8E, 0x8E, 0x8E, 0xFF,
0x90, 0x90, 0x90, 0xAD, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xBD, 0xBD, 0xBD, 0x28, 0xB0, 0xB0, 0xB0, 0xEF,
0xA2, 0xA2, 0xA2, 0xFF, 0x9A, 0x9A, 0x9A, 0xFF, 0x98, 0x98, 0x98, 0xFF,
0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF,
0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF,
0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF,
0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF,
0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF, 0x97, 0x97, 0x97, 0xFF,
0x96, 0x96, 0x96, 0xFF, 0x93, 0x93, 0x93, 0xFF, 0x8D, 0x8D, 0x8D, 0xFF,
0x86, 0x86, 0x86, 0xFF, 0x85, 0x85, 0x85, 0xEF, 0x8E, 0x8E, 0x8E, 0x28,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xAA, 0xAA, 0xAA, 0x27, 0x9D, 0x9D, 0x9D, 0xAD,
0x90, 0x90, 0x90, 0xF2, 0x8A, 0x8A, 0x8A, 0xFF, 0x87, 0x87, 0x87, 0xFF,
0x86, 0x86, 0x86, 0xFF, 0x86, 0x86, 0x86, 0xFF, 0x86, 0x86, 0x86, 0xFF,
0x86, 0x86, 0x86, 0xFF, 0x86, 0x86, 0x86, 0xFF, 0x86, 0x86, 0x86, 0xFF,
0x86, 0x86, 0x86, 0xFF, 0x86, 0x86, 0x86, 0xFF, 0x86, 0x86, 0x86, 0xFF,
0x86, 0x86, 0x86, 0xFF, 0x86, 0x86, 0x86, 0xFF, 0x86, 0x86, 0x86, 0xFF,
0x86, 0x86, 0x86, 0xFF, 0x86, 0x86, 0x86, 0xFF, 0x85, 0x85, 0x85, 0xFF,
0x84, 0x84, 0x84, 0xFF, 0x83, 0x83, 0x83, 0xF2, 0x84, 0x84, 0x84, 0xAD,
0x88, 0x88, 0x88, 0x27, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00
};
#endif // VOS_IMAGES_EMBEDDED_PROGRESSBAR_HEADER
| C | CL | 2957bb050465be8691a162edab58473d5bbbf46f0080ec24f06bf6c1d1cda3d0 |
/*
* Copyright 2020 Makani Technologies LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AVIONICS_MOTOR_FIRMWARE_CALIBRATOR_H_
#define AVIONICS_MOTOR_FIRMWARE_CALIBRATOR_H_
#include <stdint.h>
#include "avionics/motor/firmware/angle_meas.h"
#include "avionics/motor/firmware/current_limit_types.h"
#include "avionics/motor/firmware/foc.h"
#include "avionics/motor/firmware/isr.h"
uint32_t CalibrationController(const MotorIsrInput *input,
MotorState *motor_state,
MotorAngleMeas *angle_meas,
CurrentLimit *current_lmiit,
FocCurrent *foc_current_cmd,
float *current_correction);
void CalibrationSlowLoop(int16_t command);
#endif // AVIONICS_MOTOR_FIRMWARE_CALIBRATOR_H_
| C | CL | 5304ba205a1af3ae79951ac04dd3405fbcd38135d6d67f91a6a3c261e5e83a8d |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include "thingmodule.h"
#define max(a,b) (((a) (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
/* Subtract the ‘struct timeval’ values X and Y,
* storing the result in RESULT.
* Return 1 if the difference is negative, otherwise 0. */
int timeval_subtract (struct timeval *result, struct timeval*x, struct timeval *y) {
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[]){
int m = 5000;
int n = 5000;
double **data, **fuzzed;
struct timeval data_start, data_end,
calc_start, calc_end,
data_diff, calc_diff;
gettimeofday(&data_start, NULL);
data = malloc(m * sizeof(double *));
for (int i = 0; i < m; i++){
data[i] = malloc(n * sizeof(double));
}
fuzzed = malloc(m * sizeof(double *));
for (int i = 0; i < m; i++){
fuzzed[i] = malloc(n * sizeof(double));
}
printf("Generating sample data (%dx%d array), in C...\n", m, n);
for (int j = 0; j < m; j++){
for (int k = 0; k < n; k++) {
data[j][k] = pow(((float)j/10.0), 4) + pow(((float)k/20.0), 4);
}
}
gettimeofday(&data_end, NULL);
printf("Performing gradient calculation on data (%dx%d array), with results:\n", m, n);
gettimeofday(&calc_start, NULL);
del2(data, fuzzed, m, n);
gettimeofday(&calc_end, NULL);
for (int i = 0; i< min(m, n); i+=1000){
printf("%f\n", fuzzed[i][i]);
}
timeval_subtract(&data_diff, &data_end, &data_start);
timeval_subtract(&calc_diff, &calc_end, &calc_start);
printf("Summary:\n");
printf(" Data generation code segment (C) took %f seconds\n", data_diff.tv_sec + data_diff.tv_usec/1e6);
printf(" Gradient calculation code segment (C) took %f seconds\n", calc_diff.tv_sec + calc_diff.tv_usec/1e6);
printf(" Total time: %.3f seconds\n", (data_diff.tv_sec + data_diff.tv_usec/1e6) + (calc_diff.tv_sec + calc_diff.tv_usec/1e6));
// We should free() data, and fuzzed here. I'm lazy though.
return 0;
}
| C | CL | f71c54a359606d29ad4f5edc93864f86645ec0f64f1d91924353df3bfcd600ac |
/* KallistiOS ##version##
getaddrinfo.c
Copyright (C) 2014 Lawrence Sebald
Originally:
lwip/dns.c
Copyright (C) 2004 Dan Potter
*/
/* The actual code for querying the DNS was taken from the old kos-ports lwIP
port, and was originally written by Dan. This has been modified/extended a
bit. The old lwip_gethostbyname() function was reworked a lot to create the
new getaddrinfo_dns() function. In addition, the dns_parse_response()
function got a bit of a makeover too.
The implementations of getaddrinfo() and freeaddrinfo() are new to this
version of the code though.
Eventually, I'd like to add some sort of cacheing of results to this file so
that if you look something up more than once, it doesn't have to go back out
to the server to do so. But, for now, there is no local database of cached
addresses...
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <poll.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <kos/net.h>
#include <kos/dbglog.h>
/* How many attempts to make at contacting the DNS server before giving up. */
#define DNS_ATTEMPTS 4
/* How long to wait between attempts. */
#define DNS_TIMEOUT 500
/*
This performs a simple DNS A-record query. It hasn't been tested extensively
but so far it seems to work fine.
This relies on the really sketchy UDP support in the KOS lwIP port, so it
can be cleaned up later once that's improved.
We really need to be setting errno in here too...
*/
/* Basic query process:
- Send a DNS message to the server on port 53, with one query payload.
- Receive DNS message from port 53 with one or more answer payloads (hopefully).
*/
// These structs were all taken from RFC1035, page 26.
typedef struct dnsmsg {
uint16_t id; // Can be anything
uint16_t flags; // Should have 0x0100 set for query, 0x8000 for response
uint16_t qdcount, ancount, nscount, arcount;
uint8_t data[]; // Payload
} dnsmsg_t;
static uint16_t qnum = 0;
#define QTYPE_A 1
#define QTYPE_AAAA 28
/* Flags:
Query/Response (1 bit) -- 0 = Query, 1 = Response
Opcode (4 bits) -- 0 = Standard, 1 = Inverse, 2 = Status
AA (1 bit) -- authoritative answer
TC (1 bit) -- truncated message
RD (1 bit) -- recursion desired
RA (1 bit) -- recursion available
Z (1 bit) -- zero
RCODE (4 bits) -- 0 = No Error, >0 = Error
Generally a query will have 0x0100 here, and a typical
response will have 0x8180.
*/
/* Query section. A standard DNS query will have one query section
and no other payloads. There is no padding.
QNAME: one or more "labels", representing a domain name. For
example "yuna.dp.allusion.net" is "yuna, dp, allusion, net". Each
label has one length byte followed by N data bytes. A zero
length byte terminates.
QTYPE: two-byte code specifying the RR type of the query. For a
normal DNS query this should be 0x0001 (A - IPv4) or 0x001C (AAAA - IPv6).
QCLASS: two-byte code specifying the class of the query. For a
normal DNS query this should be 0x0001 (IN).
Common RR types:
A 1
NS 2
CNAME 5
SOA 6
PTR 12
MX 15
TXT 16
AAAA 28
*/
// Construct a DNS query for an A record by host name. "buf" should
// be at least 1500 bytes, to make sure there's room.
static size_t dns_make_query(const char *host, dnsmsg_t *buf, int ip4,
int ip6) {
int i, o = 0, ls, t;
// Build up the header.
buf->id = htons(qnum++);
buf->flags = htons(0x0100);
buf->qdcount = htons(ip4 + ip6);
buf->ancount = htons(0);
buf->nscount = htons(0);
buf->arcount = htons(0);
/* Fill in the question section(s). */
ls = 0;
if(ip4) {
o = ls + 1;
t = strlen(host);
for(i = 0; i <= t; i++) {
if(host[i] == '.' || i == t) {
buf->data[ls] = (o - ls) - 1;
ls = o;
o++;
}
else {
buf->data[o++] = host[i];
}
}
buf->data[ls] = 0;
// Might be unaligned now... so just build it by hand.
buf->data[o++] = (uint8_t)(QTYPE_A >> 8);
buf->data[o++] = (uint8_t)QTYPE_A;
buf->data[o++] = 0x00;
buf->data[o++] = 0x01;
ls = o;
}
if(ip6) {
o = ls + 1;
t = strlen(host);
for(i = 0; i <= t; i++) {
if(host[i] == '.' || i == t) {
buf->data[ls] = (o - ls) - 1;
ls = o;
o++;
}
else {
buf->data[o++] = host[i];
}
}
buf->data[ls] = 0;
// Might be unaligned now... so just build it by hand.
buf->data[o++] = (uint8_t)(QTYPE_AAAA >> 8);
buf->data[o++] = (uint8_t)QTYPE_AAAA;
buf->data[o++] = 0x00;
buf->data[o++] = 0x01;
}
// Return the full message size.
return (size_t)(o + sizeof(dnsmsg_t));
}
/* Resource records. A standard DNS response will have one query
section (the original one) plus an answer section. It may have
other sections but these can be ignored.
NAME: Same as QNAME, with one caveat (see below).
TYPE: Two-byte RR code (same as QTYPE).
CLASS: Two-byte class code (same as QCLASS).
TTL: Four-byte time to live interval in seconds; this entry should
not be cached longer than this.
RDLENGTH: Two-byte response length (in bytes).
RDATA: Response data, size is RDLENGTH.
For "NAME", note that this may also be a "back pointer". This is
to save space in DNS queries. Back pointers are 16-bit values with
the upper two bits set to one, and the lower bits representing an
offset within the full DNS message. So e.g., 0xc00c for the NAME
means to look at offset 12 in the full message to find the NAME
record.
For A records, RDLENGTH is 4 and RDATA is a 4-byte IP address.
When doing queries on the internet you may also get back CNAME
entries. In these responses you may have more than one answer
section (e.g. a 5 and a 1). The CNAME answer will contain the real
name, and the A answer contains the address.
*/
// Scans through and skips a label in the data payload, starting
// at the given offset. The new offset (after the label) will be
// returned.
static int dns_skip_label(dnsmsg_t *resp, int o) {
int cnt;
// End of the label?
while(resp->data[o] != 0) {
// Is it a pointer?
if((resp->data[o] & 0xc0) == 0xc0)
return o + 2;
// Skip this part.
cnt = resp->data[o++];
o += cnt;
}
// Skip the terminator
o++;
return o;
}
// Scans through and copies out a label in the data payload,
// starting at the given offset. The new offset (after the label)
// will be returned as well as the label string.
static int dns_copy_label(dnsmsg_t *resp, int o, char *outbuf) {
int cnt;
int rv = -1;
// Do each part.
outbuf[0] = 0;
for(;;) {
// Is it a pointer?
if((resp->data[o] & 0xc0) == 0xc0) {
int offs = ((resp->data[o] & ~0xc0) << 8) | resp->data[o + 1];
if(rv < 0)
rv = o + 2;
o = offs - sizeof(dnsmsg_t);
}
else {
cnt = resp->data[o++];
if(cnt) {
if(outbuf[0] != 0)
strcat(outbuf, ".");
strncat(outbuf, (char *)(resp->data + o), cnt);
o += cnt;
}
else {
break;
}
}
}
if(rv < 0)
return o;
else
return rv;
}
/* Forward declaration... */
static struct addrinfo *add_ipv4_ai(uint32_t ip, uint16_t port,
struct addrinfo *h, struct addrinfo *tail);
static struct addrinfo *add_ipv6_ai(const struct in6_addr *ip, uint16_t port,
struct addrinfo *h, struct addrinfo *tail);
// Parse a response packet from the DNS server. The IP address
// will be filled in upon a successful return, otherwise the
// return value will be <0.
static int dns_parse_response(dnsmsg_t *resp, struct addrinfo *hints,
uint16_t port, struct addrinfo **res) {
int i, o, arecs;
uint16_t flags;
char tmp[64];
uint16_t ancnt, len;
struct addrinfo *ptr = NULL;
/* Check the flags first to see if it was successful. */
flags = ntohs(resp->flags);
if(!(flags & 0x8000)) {
/* Not our response! */
return EAI_AGAIN;
}
/* Did the server report an error? */
switch(flags & 0x000f) {
case 0: /* No error */
break;
case 1: /* Format error */
case 4: /* Not implemented */
case 5: /* Refused */
default:
return EAI_FAIL;
case 3: /* Name error */
return EAI_NONAME;
case 2: /* Server failure */
return EAI_AGAIN;
}
/* Getting zero answers is also a failure. */
ancnt = ntohs(resp->ancount);
if(ancnt < 1)
return EAI_NONAME;
/* If we have any query sections (should have at least one), skip 'em. */
o = 0;
len = ntohs(resp->qdcount);
for(i = 0; i < len; i++) {
/* Skip the label. */
o = dns_skip_label(resp, o);
/* And the two type fields. */
o += 4;
}
/* Ok, now the answer section (what we're interested in). */
arecs = 0;
for(i = 0; i < ancnt; i++) {
/* Copy out the label, in case we need it. */
o = dns_copy_label(resp, o, tmp);
/* Get the type code. If it's not A or AAAA, skip it. */
if(resp->data[o] == 0 && resp->data[o + 1] == 1 &&
(hints->ai_family == AF_INET || hints->ai_family == AF_UNSPEC)) {
uint32_t addr;
o += 8;
len = (resp->data[o] << 8) | resp->data[o + 1];
o += 2;
/* Grab the address from the response. */
addr = htonl((resp->data[o] << 24) | (resp->data[o + 1] << 16) |
(resp->data[o + 2] << 8) | resp->data[o + 3]);
/* Add this address to the chain. */
if(!(ptr = add_ipv4_ai(addr, port, hints, ptr)))
/* If something goes wrong in here, it's in calling malloc, so
it is definitely a system error. */
return EAI_SYSTEM;
if(!*res)
*res = ptr;
o += len;
arecs++;
}
else if(resp->data[o] == 0 && resp->data[o + 1] == 28 &&
(hints->ai_family == AF_INET6 || hints->ai_family == AF_UNSPEC)) {
struct in6_addr addr;
o += 8;
len = (resp->data[o] << 8) | resp->data[o + 1];
o += 2;
/* Grab the address from the response. */
memcpy(addr.s6_addr, &resp->data[o], 16);
/* Add this address to the chain. */
if(!(ptr = add_ipv6_ai(&addr, port, hints, ptr)))
/* If something goes wrong in here, it's in calling malloc, so
it is definitely a system error. */
return EAI_SYSTEM;
if(!*res)
*res = ptr;
o += len;
arecs++;
}
else if(resp->data[o] == 0 && resp->data[o + 1] == 5) {
char tmp2[64];
o += 8;
len = (resp->data[o] << 8) | resp->data[o + 1];
o += 2;
o = dns_copy_label(resp, o, tmp2);
}
else {
o += 8;
len = (resp->data[o] << 8) | resp->data[o + 1];
o += 2 + len;
}
}
/* Did we find something? */
return arecs > 0 ? 0 : EAI_NONAME;
}
static int getaddrinfo_dns(const char *name, struct addrinfo *hints,
uint16_t port, struct addrinfo **res) {
struct sockaddr_in toaddr;
uint8_t qb[512];
size_t size;
int sock, rv, tries;
in_addr_t raddr;
ssize_t rsize = 0;
struct pollfd pfd;
/* Make sure we have a network device to communicate on. */
if(!net_default_dev) {
errno = ENETDOWN;
return EAI_SYSTEM;
}
/* Do we have a DNS server specified? */
if(net_default_dev->dns[0] == 0 && net_default_dev->dns[1] == 0 &&
net_default_dev->dns[2] == 0 && net_default_dev->dns[3] == 0) {
return EAI_FAIL;
}
/* Setup a query */
if(hints->ai_family == AF_UNSPEC)
/* Note: This should (in theory) work, but it seems that some resolvers
cannot handle multiple questions in one query. So... while the code
here supports multiple questions in one query, this branch will never
actually be taken -- getaddrinfo() will always make two separate
calls if we need to do both IPv4 and IPv6. */
size = dns_make_query(name, (dnsmsg_t *)qb, 1, 1);
else if(hints->ai_family == AF_INET)
size = dns_make_query(name, (dnsmsg_t *)qb, 1, 0);
else if(hints->ai_family == AF_INET6)
size = dns_make_query(name, (dnsmsg_t *)qb, 0, 1);
else {
errno = EAFNOSUPPORT;
return EAI_SYSTEM;
}
/* Make a socket to talk to the DNS server. */
if((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
return EAI_SYSTEM;
/* "Connect" the socket to the DNS server's address. */
raddr = (net_default_dev->dns[0] << 24) | (net_default_dev->dns[1] << 16) |
(net_default_dev->dns[2] << 8) | net_default_dev->dns[3];
memset(&toaddr, 0, sizeof(toaddr));
toaddr.sin_family = AF_INET;
toaddr.sin_port = htons(53);
toaddr.sin_addr.s_addr = htonl(raddr);
if(connect(sock, (struct sockaddr *)&toaddr, sizeof(toaddr))) {
close(sock);
return EAI_SYSTEM;
}
/* Set up the structure we'll use to feed to the poll function. */
pfd.fd = sock;
pfd.events = POLLIN;
pfd.revents = 0;
for(tries = 0; tries < DNS_ATTEMPTS; ++tries) {
/* Send the query to the server. */
if(send(sock, qb, size, 0) < 0) {
return EAI_SYSTEM;
}
/* Wait for the timeout to expire or for us to get the response. */
if(poll(&pfd, 1, DNS_TIMEOUT) == 1) {
/* Get the response. */
if((rsize = recv(sock, qb, 512, 0)) < 0) {
return EAI_SYSTEM;
}
break;
}
}
/* Close the socket */
close(sock);
/* If we never actually got a response, then there's probably a problem with
the server on the other end. I'm not entirely sure what to return in that
case, to be perfectly honest. I suppose that EAI_SYSTEM + ETIMEDOUT would
make the most sense, since that's really what happened... */
if(!rsize) {
errno = ETIMEDOUT;
return EAI_SYSTEM;
}
/* Parse the response. */
rv = dns_parse_response((dnsmsg_t *)qb, hints, port, res);
/* If we got something in the result, but got an error value in the return,
free whatever we got. */
if(rv != 0 && *res) {
freeaddrinfo(*res);
*res = NULL;
}
return rv;
}
/* New stuff below here... */
static struct addrinfo *add_ipv4_ai(uint32_t ip, uint16_t port,
struct addrinfo *h, struct addrinfo *tail) {
struct addrinfo *result;
struct sockaddr_in *addr;
/* Allocate all our space first. */
if(!(result = (struct addrinfo *)malloc(sizeof(struct addrinfo)))) {
return NULL;
}
if(!(addr = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in)))) {
free(result);
return NULL;
}
/* Fill in the sockaddr_in structure */
memset(addr, 0, sizeof(struct sockaddr_in));
addr->sin_family = AF_INET;
addr->sin_port = port;
addr->sin_addr.s_addr = ip;
/* Fill in the addrinfo structure */
result->ai_flags = 0;
result->ai_family = AF_INET;
result->ai_socktype = h->ai_socktype;
result->ai_protocol = h->ai_protocol;
result->ai_addrlen = sizeof(struct sockaddr_in);
result->ai_addr = (struct sockaddr *)addr;
result->ai_canonname = NULL; /* XXXX: might actually need this. */
result->ai_next = NULL;
/* Add the result to the list (or make it the list head if it is the
first entry). */
if(tail)
tail->ai_next = result;
return result;
}
static struct addrinfo *add_ipv6_ai(const struct in6_addr *ip, uint16_t port,
struct addrinfo *h, struct addrinfo *tail) {
struct addrinfo *result;
struct sockaddr_in6 *addr;
/* Allocate all our space first. */
if(!(result = (struct addrinfo *)malloc(sizeof(struct addrinfo)))) {
return NULL;
}
if(!(addr = (struct sockaddr_in6 *)malloc(sizeof(struct sockaddr_in6)))) {
free(result);
return NULL;
}
/* Fill in the sockaddr_in structure */
memset(addr, 0, sizeof(struct sockaddr_in6));
addr->sin6_family = AF_INET6;
addr->sin6_port = port;
addr->sin6_addr = *ip;
/* Fill in the addrinfo structure */
result->ai_flags = 0;
result->ai_family = AF_INET6;
result->ai_socktype = h->ai_socktype;
result->ai_protocol = h->ai_protocol;
result->ai_addrlen = sizeof(struct sockaddr_in6);
result->ai_addr = (struct sockaddr *)addr;
result->ai_canonname = NULL; /* XXXX: might actually need this. */
result->ai_next = NULL;
/* Add the result to the list (or make it the list head if it is the
first entry). */
if(tail)
tail->ai_next = result;
return result;
}
void freeaddrinfo(struct addrinfo *ai) {
struct addrinfo *next;
/* As long as we've still got something, move along the chain. */
while(ai) {
next = ai->ai_next;
/* Free up anything that might have been malloced. */
free(ai->ai_addr);
free(ai->ai_canonname);
free(ai);
/* Continue to the next entry, if any. */
ai = next;
}
}
int getaddrinfo(const char *nodename, const char *servname,
const struct addrinfo *hints, struct addrinfo **res) {
in_port_t port = 0;
unsigned long tmp;
char *endp;
int old_errno;
struct addrinfo ihints;
(void)hints;
/* What to do if res is NULL?... I'll assume we should return error... */
if(!res) {
errno = EFAULT;
return EAI_SYSTEM;
}
*res = NULL;
/* Check the input parameters... */
if(!nodename && !servname)
return EAI_NONAME;
/* We don't support service resolution from service name strings, so make
sure that if servname is specified, that it is a numeric string. */
if(servname) {
old_errno = errno;
tmp = strtoul(servname, &endp, 10);
errno = old_errno;
/* If the return value is greater than the maximum value of a 16-bit
unsigned integer or the character at *endp is not NUL, then we didn't
have a pure numeric string (or had one that wasn't valid). Return an
error in either case. */
if(tmp > 0xffff || *endp)
return EAI_NONAME;
/* Go ahead and swap the byte order of the port now, if we need to. */
port = htons((uint16_t)tmp);
}
/* Did the user give us any hints? */
if(hints)
memcpy(&ihints, hints, sizeof(ihints));
else
memset(&ihints, 0, sizeof(ihints));
/* Do we want a local address or a remote one? */
if(!nodename) {
struct addrinfo *r = NULL;
/* Is the passive flag set to indicate we want everything set up for a
bind? */
if(ihints.ai_flags & AI_PASSIVE) {
if(ihints.ai_family == AF_INET || ihints.ai_family == AF_UNSPEC) {
if(!(r = add_ipv4_ai(INADDR_ANY, port, &ihints, r)))
return EAI_SYSTEM;
*res = r;
}
if(ihints.ai_family == AF_INET6 || ihints.ai_family == AF_UNSPEC) {
if(!(r = add_ipv6_ai(&in6addr_any, port, &ihints, r))) {
freeaddrinfo(*res);
return EAI_SYSTEM;
}
if(!*res)
*res = r;
}
}
else {
if(ihints.ai_family == AF_INET || ihints.ai_family == AF_UNSPEC) {
uint32_t addr = htonl(0x7f000001);
if(!(r = add_ipv4_ai(addr, port, &ihints, r)))
return EAI_SYSTEM;
*res = r;
}
if(ihints.ai_family == AF_INET6 || ihints.ai_family == AF_UNSPEC) {
if(!(r = add_ipv6_ai(&in6addr_loopback, port, &ihints, r))) {
freeaddrinfo(*res);
return EAI_SYSTEM;
}
if(!*res)
*res = r;
}
}
return 0;
}
/* If we've gotten this far, do the lookup. */
if(ihints.ai_family == AF_UNSPEC) {
/* It seems that some resolvers really don't like multi-part questions.
So, make sure we only ever send one part at a time... */
struct addrinfo *res1 = NULL, *res2 = NULL;
int rv;
ihints.ai_family = AF_INET;
rv = getaddrinfo_dns(nodename, &ihints, port, &res1);
if(rv && rv != EAI_NONAME)
return rv;
ihints.ai_family = AF_INET6;
getaddrinfo_dns(nodename, &ihints, port, &res2);
/* Figure out what to do with the result(s). */
if(res1 && res2) {
*res = res1;
/* Go to the end of the chain. */
while(res1->ai_next) {
res1 = res1->ai_next;
}
res1->ai_next = res2;
return 0;
}
else if(res1) {
*res = res1;
return 0;
}
else if(res2) {
*res = res2;
return 0;
}
else {
return EAI_NONAME;
}
}
return getaddrinfo_dns(nodename, &ihints, port, res);
}
| C | CL | 97c8e4e0c09c095bcaf457e3b17c87b47d8957b497b2aa55fdbb9e1d9caea486 |
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <[email protected]>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
// cbor_serialize_alloc
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#include <math.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <cmocka.h>
#include "assertions.h"
#include "cbor.h"
#include "test_allocator.h"
unsigned char buffer[512];
static void test_serialize_uint8_embed(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_int8();
cbor_set_uint8(item, 0);
assert_size_equal(1, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, (unsigned char[]){0x00}, 1);
assert_size_equal(cbor_serialized_size(item), 1);
cbor_decref(&item);
}
static void test_serialize_uint8(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_int8();
cbor_set_uint8(item, 42);
assert_size_equal(2, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0x18, 0x2a}), 2);
assert_size_equal(cbor_serialized_size(item), 2);
cbor_decref(&item);
}
static void test_serialize_uint16(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_int16();
cbor_set_uint16(item, 1000);
assert_size_equal(3, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0x19, 0x03, 0xE8}), 3);
assert_size_equal(cbor_serialized_size(item), 3);
cbor_decref(&item);
}
static void test_serialize_uint32(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_int32();
cbor_set_uint32(item, 1000000);
assert_size_equal(5, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0x1A, 0x00, 0x0F, 0x42, 0x40}),
5);
assert_size_equal(cbor_serialized_size(item), 5);
cbor_decref(&item);
}
static void test_serialize_uint64(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_int64();
cbor_set_uint64(item, 1000000000000);
assert_size_equal(9, cbor_serialize(item, buffer, 512));
assert_memory_equal(
buffer,
((unsigned char[]){0x1B, 0x00, 0x00, 0x00, 0xE8, 0xD4, 0xA5, 0x10, 0x00}),
9);
assert_size_equal(cbor_serialized_size(item), 9);
cbor_decref(&item);
}
static void test_serialize_negint8_embed(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_int8();
cbor_set_uint8(item, 0);
cbor_mark_negint(item);
assert_size_equal(1, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, (unsigned char[]){0x20}, 1);
assert_size_equal(cbor_serialized_size(item), 1);
cbor_decref(&item);
}
static void test_serialize_negint8(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_int8();
cbor_set_uint8(item, 42);
cbor_mark_negint(item);
assert_size_equal(2, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0x38, 0x2a}), 2);
assert_size_equal(cbor_serialized_size(item), 2);
cbor_decref(&item);
}
static void test_serialize_negint16(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_int16();
cbor_set_uint16(item, 1000);
cbor_mark_negint(item);
assert_size_equal(3, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0x39, 0x03, 0xE8}), 3);
assert_size_equal(cbor_serialized_size(item), 3);
cbor_decref(&item);
}
static void test_serialize_negint32(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_int32();
cbor_set_uint32(item, 1000000);
cbor_mark_negint(item);
assert_size_equal(5, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0x3A, 0x00, 0x0F, 0x42, 0x40}),
5);
assert_size_equal(cbor_serialized_size(item), 5);
cbor_decref(&item);
}
static void test_serialize_negint64(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_int64();
cbor_set_uint64(item, 1000000000000);
cbor_mark_negint(item);
assert_size_equal(9, cbor_serialize(item, buffer, 512));
assert_memory_equal(
buffer,
((unsigned char[]){0x3B, 0x00, 0x00, 0x00, 0xE8, 0xD4, 0xA5, 0x10, 0x00}),
9);
assert_size_equal(cbor_serialized_size(item), 9);
cbor_decref(&item);
}
static void test_serialize_definite_bytestring(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_definite_bytestring();
unsigned char *data = malloc(256);
cbor_bytestring_set_handle(item, data, 256);
memset(data, 0, 256); /* Prevent undefined behavior in comparison */
assert_size_equal(256 + 3, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0x59, 0x01, 0x00}), 3);
assert_memory_equal(buffer + 3, data, 256);
assert_size_equal(cbor_serialized_size(item), 259);
cbor_decref(&item);
}
static void test_serialize_indefinite_bytestring(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_bytestring();
cbor_item_t *chunk = cbor_new_definite_bytestring();
unsigned char *data = malloc(256);
memset(data, 0, 256); /* Prevent undefined behavior in comparison */
cbor_bytestring_set_handle(chunk, data, 256);
assert_true(cbor_bytestring_add_chunk(item, cbor_move(chunk)));
assert_size_equal(cbor_bytestring_chunk_count(item), 1);
assert_size_equal(1 + 3 + 256 + 1, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0x5F, 0x59, 0x01, 0x00}), 4);
assert_memory_equal(buffer + 4, data, 256);
assert_memory_equal(buffer + 4 + 256, ((unsigned char[]){0xFF}), 1);
assert_size_equal(cbor_serialized_size(item), 261);
cbor_decref(&item);
}
static void test_serialize_bytestring_size_overflow(
void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_definite_bytestring();
// Fake having a huge chunk of data
unsigned char *data = malloc(1);
cbor_bytestring_set_handle(item, data, SIZE_MAX);
// Would require 1 + 8 + SIZE_MAX bytes, which overflows size_t
assert_size_equal(cbor_serialize(item, buffer, 512), 0);
assert_size_equal(cbor_serialized_size(item), 0);
cbor_decref(&item);
}
static void test_serialize_bytestring_no_space(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_definite_bytestring();
unsigned char *data = malloc(12);
cbor_bytestring_set_handle(item, data, 12);
assert_size_equal(cbor_serialize(item, buffer, 1), 0);
cbor_decref(&item);
}
static void test_serialize_indefinite_bytestring_no_space(
void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_bytestring();
cbor_item_t *chunk = cbor_new_definite_bytestring();
unsigned char *data = malloc(256);
cbor_bytestring_set_handle(chunk, data, 256);
assert_true(cbor_bytestring_add_chunk(item, cbor_move(chunk)));
// Not enough space for the leading byte
assert_size_equal(cbor_serialize(item, buffer, 0), 0);
// Not enough space for the chunk
assert_size_equal(cbor_serialize(item, buffer, 30), 0);
// Not enough space for the indef break
assert_size_equal(
cbor_serialize(item, buffer, 1 + cbor_serialized_size(chunk)), 0);
cbor_decref(&item);
}
static void test_serialize_definite_string(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_definite_string();
unsigned char *data = malloc(12);
strncpy((char *)data, "Hello world!", 12);
cbor_string_set_handle(item, data, 12);
assert_size_equal(1 + 12, cbor_serialize(item, buffer, 512));
assert_memory_equal(
buffer,
((unsigned char[]){0x6C, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 0x6F,
0x72, 0x6C, 0x64, 0x21}),
13);
assert_size_equal(cbor_serialized_size(item), 13);
cbor_decref(&item);
}
static void test_serialize_definite_string_4b_header(
void **_CBOR_UNUSED(_state)) {
#if SIZE_MAX > UINT16_MAX
cbor_item_t *item = cbor_new_definite_string();
const size_t size = (size_t)UINT16_MAX + 1;
unsigned char *data = malloc(size);
memset(data, 0, size);
cbor_string_set_handle(item, data, size);
assert_size_equal(cbor_serialized_size(item), 1 + 4 + size);
cbor_decref(&item);
#endif
}
static void test_serialize_definite_string_8b_header(
void **_CBOR_UNUSED(_state)) {
#if SIZE_MAX > UINT32_MAX
cbor_item_t *item = cbor_new_definite_string();
const size_t size = (size_t)UINT32_MAX + 1;
unsigned char *data = malloc(1);
data[0] = '\0';
cbor_string_set_handle(item, data, 1);
// Pretend that we have a big item to avoid the huge malloc
item->metadata.string_metadata.length = size;
assert_size_equal(cbor_serialized_size(item), 1 + 8 + size);
cbor_decref(&item);
#endif
}
static void test_serialize_indefinite_string(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_string();
cbor_item_t *chunk = cbor_new_definite_string();
unsigned char *data = malloc(12);
strncpy((char *)data, "Hello world!", 12);
cbor_string_set_handle(chunk, data, 12);
assert_true(cbor_string_add_chunk(item, cbor_move(chunk)));
assert_size_equal(cbor_string_chunk_count(item), 1);
assert_size_equal(15, cbor_serialize(item, buffer, 512));
assert_memory_equal(
buffer,
((unsigned char[]){0x7F, 0x6C, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77,
0x6F, 0x72, 0x6C, 0x64, 0x21, 0xFF}),
15);
assert_size_equal(cbor_serialized_size(item), 15);
cbor_decref(&item);
}
static void test_serialize_string_no_space(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_definite_string();
unsigned char *data = malloc(12);
memset(data, 0, 12);
cbor_string_set_handle(item, data, 12);
assert_size_equal(cbor_serialize(item, buffer, 1), 0);
cbor_decref(&item);
}
static void test_serialize_indefinite_string_no_space(
void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_string();
cbor_item_t *chunk = cbor_new_definite_string();
unsigned char *data = malloc(256);
memset(data, 0, 256);
cbor_string_set_handle(chunk, data, 256);
assert_true(cbor_string_add_chunk(item, cbor_move(chunk)));
// Not enough space for the leading byte
assert_size_equal(cbor_serialize(item, buffer, 0), 0);
// Not enough space for the chunk
assert_size_equal(cbor_serialize(item, buffer, 30), 0);
// Not enough space for the indef break
assert_size_equal(
cbor_serialize(item, buffer, 1 + cbor_serialized_size(chunk)), 0);
cbor_decref(&item);
}
static void test_serialize_definite_array(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_definite_array(2);
cbor_item_t *one = cbor_build_uint8(1);
cbor_item_t *two = cbor_build_uint8(2);
assert_true(cbor_array_push(item, one));
assert_true(cbor_array_set(item, 1, two));
assert_true(cbor_array_replace(item, 0, one));
assert_size_equal(3, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0x82, 0x01, 0x02}), 3);
assert_size_equal(cbor_serialized_size(item), 3);
cbor_decref(&item);
cbor_decref(&one);
cbor_decref(&two);
}
static void test_serialize_array_no_space(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_array();
cbor_item_t *one = cbor_build_uint8(1);
assert_true(cbor_array_push(item, one));
assert_size_equal(cbor_serialized_size(item), 3);
// Not enough space for the leading byte
assert_size_equal(0, cbor_serialize(item, buffer, 0));
// Not enough space for the item
assert_size_equal(0, cbor_serialize(item, buffer, 1));
// Not enough space for the indef break
assert_size_equal(0, cbor_serialize(item, buffer, 2));
cbor_decref(&item);
cbor_decref(&one);
}
static void test_serialize_indefinite_array(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_array();
cbor_item_t *one = cbor_build_uint8(1);
cbor_item_t *two = cbor_build_uint8(2);
assert_true(cbor_array_push(item, one));
assert_true(cbor_array_push(item, two));
assert_size_equal(4, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0x9F, 0x01, 0x02, 0xFF}), 4);
assert_size_equal(cbor_serialized_size(item), 4);
cbor_decref(&item);
cbor_decref(&one);
cbor_decref(&two);
}
static void test_serialize_definite_map(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_definite_map(2);
cbor_item_t *one = cbor_build_uint8(1);
cbor_item_t *two = cbor_build_uint8(2);
assert_true(cbor_map_add(item, (struct cbor_pair){.key = one, .value = two}));
assert_true(cbor_map_add(item, (struct cbor_pair){.key = two, .value = one}));
assert_size_equal(5, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0xA2, 0x01, 0x02, 0x02, 0x01}),
5);
assert_size_equal(cbor_serialized_size(item), 5);
cbor_decref(&item);
cbor_decref(&one);
cbor_decref(&two);
}
static void test_serialize_indefinite_map(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_map();
cbor_item_t *one = cbor_build_uint8(1);
cbor_item_t *two = cbor_build_uint8(2);
assert_true(cbor_map_add(item, (struct cbor_pair){.key = one, .value = two}));
assert_true(cbor_map_add(item, (struct cbor_pair){.key = two, .value = one}));
assert_size_equal(6, cbor_serialize(item, buffer, 512));
assert_memory_equal(
buffer, ((unsigned char[]){0xBF, 0x01, 0x02, 0x02, 0x01, 0xFF}), 6);
assert_size_equal(cbor_serialized_size(item), 6);
cbor_decref(&item);
cbor_decref(&one);
cbor_decref(&two);
}
static void test_serialize_map_no_space(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_map();
cbor_item_t *one = cbor_build_uint8(1);
cbor_item_t *two = cbor_build_uint8(2);
assert_true(cbor_map_add(item, (struct cbor_pair){.key = one, .value = two}));
assert_size_equal(cbor_serialized_size(item), 4);
// Not enough space for the leading byte
assert_size_equal(cbor_serialize(item, buffer, 0), 0);
// Not enough space for the key
assert_size_equal(cbor_serialize(item, buffer, 1), 0);
// Not enough space for the value
assert_size_equal(cbor_serialize(item, buffer, 2), 0);
// Not enough space for the indef break
assert_size_equal(cbor_serialize(item, buffer, 3), 0);
cbor_decref(&item);
cbor_decref(&one);
cbor_decref(&two);
}
static void test_serialize_tags(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_tag(21);
cbor_item_t *one = cbor_build_uint8(1);
cbor_tag_set_item(item, one);
assert_size_equal(2, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0xD5, 0x01}), 2);
assert_size_equal(cbor_serialized_size(item), 2);
cbor_decref(&item);
cbor_decref(&one);
}
static void test_serialize_tags_no_space(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_tag(21);
cbor_item_t *one = cbor_build_uint8(1);
cbor_tag_set_item(item, one);
assert_size_equal(cbor_serialized_size(item), 2);
// Not enough space for the leading byte
assert_size_equal(cbor_serialize(item, buffer, 0), 0);
// Not enough space for the item
assert_size_equal(cbor_serialize(item, buffer, 1), 0);
cbor_decref(&item);
cbor_decref(&one);
}
static void test_serialize_half(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_float2();
cbor_set_float2(item, NAN);
assert_size_equal(3, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0xF9, 0x7E, 0x00}), 3);
assert_size_equal(cbor_serialized_size(item), 3);
cbor_decref(&item);
}
static void test_serialize_single(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_float4();
cbor_set_float4(item, 100000.0f);
assert_size_equal(5, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0xFA, 0x47, 0xC3, 0x50, 0x00}),
5);
assert_size_equal(cbor_serialized_size(item), 5);
cbor_decref(&item);
}
static void test_serialize_double(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_float8();
cbor_set_float8(item, -4.1);
assert_size_equal(9, cbor_serialize(item, buffer, 512));
assert_memory_equal(
buffer,
((unsigned char[]){0xFB, 0xC0, 0x10, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66}),
9);
assert_size_equal(cbor_serialized_size(item), 9);
cbor_decref(&item);
}
static void test_serialize_ctrl(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_undef();
assert_size_equal(1, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0xF7}), 1);
assert_size_equal(cbor_serialized_size(item), 1);
cbor_decref(&item);
}
static void test_serialize_long_ctrl(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_ctrl();
cbor_set_ctrl(item, 254);
assert_size_equal(2, cbor_serialize(item, buffer, 512));
assert_memory_equal(buffer, ((unsigned char[]){0xF8, 0xFE}), 2);
assert_size_equal(cbor_serialized_size(item), 2);
cbor_decref(&item);
}
static void test_auto_serialize(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_definite_array(4);
for (size_t i = 0; i < 4; i++) {
assert_true(cbor_array_push(item, cbor_move(cbor_build_uint64(0))));
}
unsigned char *output;
size_t output_size;
assert_size_equal(cbor_serialize_alloc(item, &output, &output_size), 37);
assert_size_equal(output_size, 37);
assert_size_equal(cbor_serialized_size(item), 37);
assert_memory_equal(output, ((unsigned char[]){0x84, 0x1B}), 2);
cbor_decref(&item);
_cbor_free(output);
}
static void test_auto_serialize_no_size(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_build_uint8(1);
unsigned char *output;
assert_size_equal(cbor_serialize_alloc(item, &output, NULL), 1);
assert_memory_equal(output, ((unsigned char[]){0x01}), 1);
assert_size_equal(cbor_serialized_size(item), 1);
cbor_decref(&item);
_cbor_free(output);
}
static void test_auto_serialize_too_large(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_string();
cbor_item_t *chunk = cbor_new_definite_string();
assert_true(cbor_string_add_chunk(item, chunk));
// Pretend the chunk is huge
chunk->metadata.string_metadata.length = SIZE_MAX;
assert_true(SIZE_MAX + 2 == 1);
assert_size_equal(cbor_serialized_size(item), 0);
unsigned char *output;
size_t output_size;
assert_size_equal(cbor_serialize_alloc(item, &output, &output_size), 0);
assert_size_equal(output_size, 0);
assert_null(output);
chunk->metadata.string_metadata.length = 0;
cbor_decref(&chunk);
cbor_decref(&item);
}
static void test_auto_serialize_alloc_fail(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_build_uint8(42);
WITH_FAILING_MALLOC({
unsigned char *output;
size_t output_size;
assert_size_equal(cbor_serialize_alloc(item, &output, &output_size), 0);
assert_size_equal(output_size, 0);
assert_null(output);
});
cbor_decref(&item);
}
static void test_auto_serialize_zero_len_bytestring(
void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_build_bytestring((cbor_data) "", 0);
unsigned char *output;
assert_size_equal(cbor_serialize_alloc(item, &output, NULL), 1);
assert_memory_equal(output, ((unsigned char[]){0x40}), 1);
assert_size_equal(cbor_serialized_size(item), 1);
cbor_decref(&item);
_cbor_free(output);
}
static void test_auto_serialize_zero_len_string(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_build_string("");
unsigned char *output;
assert_size_equal(cbor_serialize_alloc(item, &output, NULL), 1);
assert_memory_equal(output, ((unsigned char[]){0x60}), 1);
assert_size_equal(cbor_serialized_size(item), 1);
cbor_decref(&item);
_cbor_free(output);
}
static void test_auto_serialize_zero_len_bytestring_chunk(
void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_bytestring();
assert_true(cbor_bytestring_add_chunk(
item, cbor_move(cbor_build_bytestring((cbor_data) "", 0))));
unsigned char *output;
assert_size_equal(cbor_serialize_alloc(item, &output, NULL), 3);
assert_memory_equal(output, ((unsigned char[]){0x5f, 0x40, 0xff}), 3);
assert_size_equal(cbor_serialized_size(item), 3);
cbor_decref(&item);
_cbor_free(output);
}
static void test_auto_serialize_zero_len_string_chunk(
void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_string();
assert_true(cbor_string_add_chunk(item, cbor_move(cbor_build_string(""))));
unsigned char *output;
assert_size_equal(cbor_serialize_alloc(item, &output, NULL), 3);
assert_memory_equal(output, ((unsigned char[]){0x7f, 0x60, 0xff}), 3);
assert_size_equal(cbor_serialized_size(item), 3);
cbor_decref(&item);
_cbor_free(output);
}
static void test_auto_serialize_zero_len_array(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_definite_array(0);
unsigned char *output;
assert_size_equal(cbor_serialize_alloc(item, &output, NULL), 1);
assert_memory_equal(output, ((unsigned char[]){0x80}), 1);
assert_size_equal(cbor_serialized_size(item), 1);
cbor_decref(&item);
_cbor_free(output);
}
static void test_auto_serialize_zero_len_indef_array(
void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_array();
unsigned char *output;
assert_size_equal(cbor_serialize_alloc(item, &output, NULL), 2);
assert_memory_equal(output, ((unsigned char[]){0x9f, 0xff}), 2);
assert_size_equal(cbor_serialized_size(item), 2);
cbor_decref(&item);
_cbor_free(output);
}
static void test_auto_serialize_zero_len_map(void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_definite_map(0);
unsigned char *output;
assert_size_equal(cbor_serialize_alloc(item, &output, NULL), 1);
assert_memory_equal(output, ((unsigned char[]){0xa0}), 1);
assert_size_equal(cbor_serialized_size(item), 1);
cbor_decref(&item);
_cbor_free(output);
}
static void test_auto_serialize_zero_len_indef_map(
void **_CBOR_UNUSED(_state)) {
cbor_item_t *item = cbor_new_indefinite_map();
unsigned char *output;
assert_size_equal(cbor_serialize_alloc(item, &output, NULL), 2);
assert_memory_equal(output, ((unsigned char[]){0xbf, 0xff}), 2);
assert_size_equal(cbor_serialized_size(item), 2);
cbor_decref(&item);
_cbor_free(output);
}
int main(void) {
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_serialize_uint8_embed),
cmocka_unit_test(test_serialize_uint8),
cmocka_unit_test(test_serialize_uint16),
cmocka_unit_test(test_serialize_uint32),
cmocka_unit_test(test_serialize_uint64),
cmocka_unit_test(test_serialize_negint8_embed),
cmocka_unit_test(test_serialize_negint8),
cmocka_unit_test(test_serialize_negint16),
cmocka_unit_test(test_serialize_negint32),
cmocka_unit_test(test_serialize_negint64),
cmocka_unit_test(test_serialize_definite_bytestring),
cmocka_unit_test(test_serialize_indefinite_bytestring),
cmocka_unit_test(test_serialize_bytestring_size_overflow),
cmocka_unit_test(test_serialize_bytestring_no_space),
cmocka_unit_test(test_serialize_indefinite_bytestring_no_space),
cmocka_unit_test(test_serialize_definite_string),
cmocka_unit_test(test_serialize_definite_string_4b_header),
cmocka_unit_test(test_serialize_definite_string_8b_header),
cmocka_unit_test(test_serialize_indefinite_string),
cmocka_unit_test(test_serialize_string_no_space),
cmocka_unit_test(test_serialize_indefinite_string_no_space),
cmocka_unit_test(test_serialize_definite_array),
cmocka_unit_test(test_serialize_indefinite_array),
cmocka_unit_test(test_serialize_array_no_space),
cmocka_unit_test(test_serialize_definite_map),
cmocka_unit_test(test_serialize_indefinite_map),
cmocka_unit_test(test_serialize_map_no_space),
cmocka_unit_test(test_serialize_tags),
cmocka_unit_test(test_serialize_tags_no_space),
cmocka_unit_test(test_serialize_half),
cmocka_unit_test(test_serialize_single),
cmocka_unit_test(test_serialize_double),
cmocka_unit_test(test_serialize_ctrl),
cmocka_unit_test(test_serialize_long_ctrl),
cmocka_unit_test(test_auto_serialize),
cmocka_unit_test(test_auto_serialize_no_size),
cmocka_unit_test(test_auto_serialize_too_large),
cmocka_unit_test(test_auto_serialize_alloc_fail),
cmocka_unit_test(test_auto_serialize_zero_len_bytestring),
cmocka_unit_test(test_auto_serialize_zero_len_string),
cmocka_unit_test(test_auto_serialize_zero_len_bytestring_chunk),
cmocka_unit_test(test_auto_serialize_zero_len_string_chunk),
cmocka_unit_test(test_auto_serialize_zero_len_array),
cmocka_unit_test(test_auto_serialize_zero_len_indef_array),
cmocka_unit_test(test_auto_serialize_zero_len_map),
cmocka_unit_test(test_auto_serialize_zero_len_indef_map),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
| C | CL | c79e19f87547db9772bde4b1d076f85cefc90405dd51091494bc16ee80d2c21c |
/*
Advanced Computing Center for Research and Education Proprietary License
Version 1.0 (April 2006)
Copyright (c) 2006, Advanced Computing Center for Research and Education,
Vanderbilt University, All rights reserved.
This Work is the sole and exclusive property of the Advanced Computing Center
for Research and Education department at Vanderbilt University. No right to
disclose or otherwise disseminate any of the information contained herein is
granted by virtue of your possession of this software except in accordance with
the terms and conditions of a separate License Agreement entered into with
Vanderbilt University.
THE AUTHOR OR COPYRIGHT HOLDERS PROVIDES THE "WORK" ON AN "AS IS" BASIS,
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, TITLE, FITNESS FOR A PARTICULAR
PURPOSE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Vanderbilt University
Advanced Computing Center for Research and Education
230 Appleton Place
Nashville, TN 37203
http://www.accre.vanderbilt.edu
*/
#include <stdlib.h>
#include <string.h>
#include <apr_pools.h>
#include <apr_thread_proc.h>
#include "ibp.h"
#include "ibp_misc.h"
#include "host_portal.h"
#include "log.h"
//=============================================================
//*************************************************************
// iovec_sync_thread - Actual routine that performs the I/O
//*************************************************************
void *iovec_sync_thread(apr_thread_t *th, void *data)
{
oplist_t *oplist = (oplist_t *)data;
ibp_op_t *op;
int finished, cmd_count, nbytes;
ibp_timer_t timer, timer2;
ibp_capstatus_t astat;
ibp_capset_t *capset;
ibp_op_rw_t *rw_op;
ibp_op_copy_t *copy_op;
ibp_op_alloc_t *alloc_op;
ibp_op_probe_t *probe_op;
ibp_op_depot_modify_t *dm_op;
ibp_op_depot_inq_t *di_op;
int err;
memset(&astat, 0, sizeof(ibp_capstatus_t));
cmd_count = 0;
finished = 0;
while (finished == 0) {
lock_oplist(oplist);
op = (ibp_op_t *)get_ele_data(oplist->list);
move_down(oplist->list);
unlock_oplist(oplist);
if (op == NULL) {
finished = 1;
} else {
cmd_count++;
timer.ClientTimeout = op->hop.timeout;
timer.ServerSync = op->hop.timeout;
switch (op->primary_cmd) {
case IBP_LOAD:
rw_op = &(op->rw_op);
nbytes = IBP_load(rw_op->cap, &timer, rw_op->buf, rw_op->size, rw_op->offset);
if (nbytes != rw_op->size) {
log_printf(0, "iovec_sync_thread: IBP_load error! nbytes=%d error=%d cap=%s\n", nbytes, IBP_errno, rw_op->cap);
}
break;
case IBP_WRITE:
rw_op = &(op->rw_op);
nbytes = IBP_write(rw_op->cap, &timer, rw_op->buf, rw_op->size, rw_op->offset);
if (nbytes != rw_op->size) {
log_printf(0, "iovec_sync_thread: IBP_write error! nbytes=%d error=%d\n", nbytes, IBP_errno);
}
break;
case IBP_STORE:
rw_op = &(op->rw_op);
nbytes = IBP_store(rw_op->cap, &timer, rw_op->buf, rw_op->size);
if (nbytes != rw_op->size) {
log_printf(0, "iovec_sync_thread: IBP_store error! nbytes=%d error=%d\n", nbytes, IBP_errno);
}
break;
case IBP_SEND:
copy_op = &(op->copy_op);
timer2.ClientTimeout = copy_op->dest_client_timeout;
timer2.ServerSync = copy_op->dest_timeout;
nbytes = IBP_copy(copy_op->srccap, copy_op->destcap, &timer, &timer2, copy_op->len, copy_op->src_offset);
if (nbytes != copy_op->len) {
log_printf(0, "iovec_sync_thread: IBP_write error! nbytes=%d error=%d\n", nbytes, IBP_errno);
}
break;
case IBP_ALLOCATE:
alloc_op = &(op->alloc_op);
if ((capset = IBP_allocate(alloc_op->depot, &timer, alloc_op->size, alloc_op->attr)) == NULL) {
log_printf(0, "iovec_sync_thread: ibp_allocate error! * ibp_errno=%d\n", IBP_errno);
} else {
memcpy(alloc_op->caps, capset, sizeof(ibp_capset_t));
free(capset);
}
break;
case IBP_MANAGE:
probe_op = &(op->probe_op);
err = IBP_manage(probe_op->cap, &timer, op->sub_cmd, IBP_READCAP, &astat);
if (err != 0) {
log_printf(0, "iovec_sync_thread: IBP_manage error! return=%d error=%d\n", err, IBP_errno);
}
break;
case IBP_STATUS:
if (op->sub_cmd == IBP_ST_INQ) {
dm_op = &(op->depot_modify_op);
IBP_status(dm_op->depot, op->sub_cmd, &timer, dm_op->password,
dm_op->max_hard, dm_op->max_soft, dm_op->max_duration);
} else {
di_op = &(op->depot_inq_op);
di_op->di = IBP_status(di_op->depot, op->sub_cmd, &timer, di_op->password, 0, 0, 0);
}
if (IBP_errno != IBP_OK) {
log_printf(0, "iovec_sync_thread: IBP_status error! error=%d\n", IBP_errno);
}
default:
log_printf(0, "iovec_sync_thread: Unknown command: %d sub_cmd=%d \n", op->primary_cmd, op->sub_cmd);
IBP_errno = IBP_E_INTERNAL;
}
oplist_mark_completed(oplist, op, IBP_errno);
}
// log_printf(15, "iovec_sync_thread: cmd_count=%d\n", cmd_count);
}
log_printf(1, "iovec_sync_thread: Total commands processed: %d\n", cmd_count);
apr_thread_exit(th, 0);
return(NULL);
}
//*************************************************************
// ibp_sync_execute - Handles the sync iovec operations
//*************************************************************
int ibp_sync_execute(oplist_t *oplist, int nthreads)
{
apr_thread_t *thread[nthreads];
apr_pool_t *mpool;
apr_status_t dummy;
int i;
log_printf(15, "ibp_sync_execute: Start! ncommands=%d\n", stack_size(oplist->list));
lock_oplist(oplist);
sort_oplist(oplist); //** Sort the work
move_to_top(oplist->list);
unlock_oplist(oplist);
apr_pool_create(&mpool, NULL); //** Create the memory pool
//** launch the threads **
for (i=0; i<nthreads; i++) {
apr_thread_create(&(thread[i]), NULL, iovec_sync_thread, (void *)oplist, mpool);
}
//** Wait for them to complete **
for (i=0; i<nthreads; i++) {
apr_thread_join(&dummy, thread[i]);
}
apr_pool_destroy(mpool); //** Destroy the pool
if (oplist_nfailed(oplist) == 0) {
return(IBP_OK);
} else {
return(IBP_E_GENERIC);
}
}
| C | CL | e96540a064862179d1feccdc326c9a69f65bd074b4ca74b711ddfe3116e33c6d |
/*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* System includes */
#include <getopt.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* Local includes */
#include <conway.h>
#include <conwayio.h>
#define VERSION "1.0b\0"
#define ERROR_BAD_SIZE 3
#define ERROR_NEEDED_SIZE 4
#define ERROR_NEGATIVE_DELAY 5
/* Prototypes */
void run(conway_t *board, int generations, int delay);
void fprint_help(FILE *fp);
void fprint_version(FILE *fp);
void exit_with_reason(int error_code, char *error_msg);
/* Main entry */
int main(int argc, char *argv[])
{
conway_t board;
int num_rows = 20, num_cols = 75;
int generations = -1;
int delay = 1;/*seconds*/
bool randomize = false;
char *filename = NULL;
char *token = NULL;
int c;
/* Options:
* -d Delay seconds between iterations, or 0 for none
* -g Maximum number of generations, or -1 to infinite
* -s Board size in "nxm" format
* -r Randomize board
* -f File to get board from, or stdin (implicit dimensions)
* -h Show help
* -v Show version
*/
const char *short_opt = "d:g:f:s:rhv";
struct option long_opt[] = {
{"delay", required_argument, NULL, 'd'},
{"file", required_argument, NULL, 'f'},
{"gens", required_argument, NULL, 'g'},
{"size", required_argument, NULL, 's'},
{"random", no_argument, NULL, 'r'},
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
};
while ((c = getopt_long(argc, argv, short_opt, long_opt, NULL)) != -1) {
switch (c) {
case -1:
case 0:
break;
case 'd':
delay = atoi(optarg);
if (delay < 0) {
exit_with_reason(ERROR_NEGATIVE_DELAY,
"Delay time must be unsinged integer.");
}
break;
case 'g':
generations = atoi(optarg);
break;
case 'f':
filename = optarg; // TODO
exit_with_reason(-1, "Feature not implemented yet. Use '-r' option :(");
break;
case 's':
if ((token = strtok(optarg, "x"))) {
num_cols = atoi(token);
if ((token = strtok(NULL, "x"))) {
num_rows = atoi(token);
}
}
if (num_rows <= 0 || num_cols <= 0) {
exit_with_reason(ERROR_BAD_SIZE,
"Enter size in 'mxn' format (positive values).");
}
break;
case 'r':
randomize = true;
if (num_rows <= 0 || num_cols <= 0) {
exit_with_reason(ERROR_NEEDED_SIZE,
"Needed size before using random option.");
}
break;
case 'v':
fprint_version(stdout);
return 0;
case 'h':
fprint_help(stdout);
return 0;
case '?':
default:
fprint_help(stdout);
return 1;
}
}
conway_init(&board, num_rows, num_cols);
if (randomize) {
conway_random(&board, time(NULL));
} else if (filename) {
}
run(&board, generations, delay);
conway_destroy(&board);
return 0;
}
void run(conway_t *board, int generations, int delay)
{
conway_draw_universe(board);/* 0th generation */
while (conway_has_life(board) && generations) {
sleep(delay);
conway_evolve(board);
conway_draw_universe(board);
if (generations > 0) {
generations--;
}
}
}
void fprint_help(FILE *fp)
{
fprintf(fp,"Options:\n");
fprintf(fp, " --delay, -d Delay seconds between iterations, or 0 for none\n");
fprintf(fp, " --gens, -g Maximum number of generations, or -1 to infinite\n");
fprintf(fp, " --size, -s Board size in \"nxm\" format\n");
fprintf(fp, " --random, -r Randomize board\n");
fprintf(fp, " --file, -f File to get board from, or stdin (implicit dimensions)\n");
fprintf(fp, " --help, -h Show help and exits\n");
fprintf(fp, " --version -v Show version and exits\n");
fprintf(fp, "\n");
fprintf(fp, "Default values:\n");
fprintf(fp, " * delay: 1 second\n");
fprintf(fp, " * generations: infinite\n");
fprintf(fp, " * size: 75x20\n");
fprintf(fp, "\n");
}
void fprint_version(FILE *fp)
{
fprintf(fp, "Version: %s\n", VERSION);
}
void exit_with_reason(int error_code, char *error_msg)
{
fprintf(stderr, "Error: %s\n", error_msg);
exit(error_code);
}
/*
// Glider
conway_alive(&board, 3, 14);
conway_alive(&board, 4, 16);
conway_alive(&board, 5, 14);
conway_alive(&board, 5, 15);
conway_alive(&board, 5, 16);
// Tetra-blinker
conway_alive(&board, 16, 22);
conway_alive(&board, 17, 22);
conway_alive(&board, 18, 22);
conway_alive(&board, 14, 24);
conway_alive(&board, 14, 25);
conway_alive(&board, 14, 26);
conway_alive(&board, 20, 24);
conway_alive(&board, 20, 25);
conway_alive(&board, 20, 26);
conway_alive(&board, 16, 28);
conway_alive(&board, 17, 28);
conway_alive(&board, 18, 28);
*/
| C | CL | 4cd709e961fba35922e97e5e4bc4a5314bf125460a347ca1f45a54091980edc7 |
static char *rcsid = "$Id: UiPageSettings.c,v 1.1 1992/03/26 18:13:50 kny Exp kny $";
#include "UiIncludes.h"
static void uibindpsvariables(void);
static void uiupdatepsvariables(void);
static Widget uicreatepsformdialog();
static Widget uicreatepslabel(Widget parent);
static Widget
uicreatepsmargin(Widget parent, Widget topwdg, char *name,
int position);
static Widget uicreatepsseparator(Widget formwdg, Widget topwdg);
static Widget uicreatepsusefixed(Widget parent, Widget topwdg);
static Widget uicreatepssinglepage(Widget parent, Widget topwdg);
static void uicreatepsbuttons(Widget formwdg, Widget topwdg);
static void uipagesettingsmargincb(char *address, HText_t * htext,
HTextObject_t * htextobject,
void *parameter);
static void uipagesettingsusefixedcb(char *address, HText_t * htext,
HTextObject_t * htextobject,
void *parameter);
static void uipagesettingsbuttoncb(char *address, HText_t * htext,
HTextObject_t * htextobject,
void *parameter);
int UiDisplayPageSettingsDialog(type)
int type;
{
uiPageSettingsGfx_t *psgfx = &uiTopLevel.PageSettingsGfx;
Widget separatorwdg;
uibindpsvariables();
if (psgfx->FormWdg) {
XtMapWidget(XtParent(psgfx->FormWdg));
uiWidgetPlacement(XtParent(psgfx->FormWdg),
uiTopLevel.GlobalSettings.PageSettingsPlacement);
uiupdatepsvariables();
return UI_OK;
}
psgfx->FormWdg = uicreatepsformdialog();
psgfx->LabelWdg = uicreatepslabel(psgfx->FormWdg);
psgfx->LeftMarginWdg = uicreatepsmargin(psgfx->FormWdg, psgfx->LabelWdg,
"Left", UI_LEFT);
psgfx->RightMarginWdg =
uicreatepsmargin(psgfx->FormWdg, psgfx->LeftMarginWdg,
"Right", UI_LEFT);
psgfx->TopMarginWdg = uicreatepsmargin(psgfx->FormWdg, psgfx->LabelWdg,
"Top", UI_RIGHT);
psgfx->BottomMarginWdg =
uicreatepsmargin(psgfx->FormWdg, psgfx->TopMarginWdg,
"Bottom", UI_RIGHT);
separatorwdg = uicreatepsseparator(psgfx->FormWdg, psgfx->RightMarginWdg);
psgfx->UseFixedWdg = uicreatepsusefixed(psgfx->FormWdg,
separatorwdg);
psgfx->SinglePageWdg = uicreatepssinglepage(psgfx->FormWdg,
psgfx->UseFixedWdg);
separatorwdg = uicreatepsseparator(psgfx->FormWdg, psgfx->SinglePageWdg);
uicreatepsbuttons(psgfx->FormWdg, separatorwdg);
XtManageChild(psgfx->FormWdg);
XtRealizeWidget(XtParent(psgfx->FormWdg));
uiWidgetPlacement(XtParent(psgfx->FormWdg),
uiTopLevel.GlobalSettings.PageSettingsPlacement);
uiupdatepsvariables();
return UI_OK;
}
void uiPageSettingsUpdateDialog()
{
if (uiTopLevel.PageSettingsGfx.FormWdg) {
if (uiPageInfo.CurrentPage) {
uibindpsvariables();
uiupdatepsvariables();
} else
XtUnmapWidget(XtParent(uiTopLevel.PageSettingsGfx.FormWdg));
}
}
static void uibindpsvariables()
{
UiBindVariable("TopMargin",
(void *) &uiPageInfo.CurrentPage->Settings.TopMargin,
uiVTint);
UiBindVariable("BottomMargin",
(void *) &uiPageInfo.CurrentPage->Settings.BottomMargin,
uiVTint);
UiBindVariable("LeftMargin",
(void *) &uiPageInfo.CurrentPage->Settings.LeftMargin,
uiVTint);
UiBindVariable("RightMargin",
(void *) &uiPageInfo.CurrentPage->Settings.RightMargin,
uiVTint);
UiBindVariable("UseFixed",
(void *) &uiPageInfo.CurrentPage->Settings.UseFixed,
uiVTint);
UiBindVariable("FixedWidth",
(void *) &uiPageInfo.CurrentPage->Settings.FixedWidth,
uiVTint);
UiBindVariable("OnePageMode",
(void *) &uiPageInfo.CurrentPage->Settings.OnePageMode,
uiVTint);
}
static void uiupdatepsvariables()
{
UiUpdateVariable("TopMargin");
UiUpdateVariable("BottomMargin");
UiUpdateVariable("LeftMargin");
UiUpdateVariable("RightMargin");
UiUpdateVariable("UseFixed");
UiUpdateVariable("FixedWidth");
UiUpdateVariable("OnePageMode");
}
static Widget
uicreatepsformdialog()
{
ArgList args;
Cardinal nargs;
Widget formwdg;
Widget topwdg;
topwdg = XtCreateApplicationShell("PageSettings",
topLevelShellWidgetClass,
NULL, 0);
XtVaSetValues(topwdg,
XmNtitle, UI_SETTINGS_TITLE, NULL);
args = uiVaSetArgs(&nargs,
XmNresizePolicy, XmRESIZE_NONE,
XmNautoUnmanage, FALSE, NULL);
formwdg = XmCreateForm(topwdg, "PageSettings", args, nargs);
return formwdg;
}
static Widget
uicreatepslabel(formwdg)
Widget formwdg;
{
ArgList args;
Cardinal nargs;
XmString labelstr;
Widget labelwdg;
labelstr = XmStringCreateSimple("Define Margins:");
args = uiVaSetArgs(&nargs,
XmNlabelString, labelstr,
XmNtopAttachment, XmATTACH_FORM,
XmNtopOffset, UI_PAGESETTINGS_WDG_OFFSET,
XmNleftAttachment, XmATTACH_FORM,
XmNrightAttachment, XmATTACH_FORM, NULL);
labelwdg = XmCreateLabelGadget(formwdg, "TextLabel", args, nargs);
XtManageChild(labelwdg);
XmStringFree(labelstr);
return labelwdg;
}
static uiActionData_t uiactiondata[8] =
{
{"LArrowDown", (uiPage_t *) NULL},
{"LArrowUp", (uiPage_t *) NULL},
{"RArrowDown", (uiPage_t *) NULL},
{"RArrowUp", (uiPage_t *) NULL},
{"TArrowDown", (uiPage_t *) NULL},
{"TArrowUp", (uiPage_t *) NULL},
{"BArrowDown", (uiPage_t *) NULL},
{"BArrowUp", (uiPage_t *) NULL}
};
static Widget uipstextwidget[] =
{
(Widget) NULL,
(Widget) NULL,
(Widget) NULL,
(Widget) NULL
};
static Widget
uicreatepsmargin(formwdg, topwdg, name, pos)
Widget formwdg;
Widget topwdg;
char *name;
int pos;
{
ArgList args;
Cardinal nargs;
XmString labelstr;
static int callnr = 0;
Widget marginformwdg, labelwdg;
Widget margindownwdg, marginupwdg, textwdg;
static char textvar[4][13]; /* strlen("BottomMargin") */
char *text;
args = uiVaSetArgs(&nargs,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, topwdg,
XmNtopOffset, UI_PAGESETTINGS_WDG_OFFSET,
XmNleftAttachment, XmATTACH_POSITION,
XmNleftPosition, 5 + 50 * (pos == UI_RIGHT),
XmNrightAttachment, XmATTACH_POSITION,
XmNrightPosition, 45 + 50 * (pos == UI_RIGHT), NULL);
marginformwdg = XmCreateForm(formwdg, "MarginForm", args, nargs);
XtManageChild(marginformwdg);
labelstr = XmStringCreateSimple(name);
args = uiVaSetArgs(&nargs,
XmNlabelString, labelstr,
XmNalignment, XmALIGNMENT_BEGINNING,
XmNtopAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_POSITION,
XmNleftPosition, 5,
XmNrightAttachment, XmATTACH_POSITION,
XmNrightPosition, 40,
XmNbottomAttachment, XmATTACH_FORM, NULL);
labelwdg = XmCreateLabelGadget(marginformwdg, "TextLabel", args, nargs);
XtManageChild(labelwdg);
XmStringFree(labelstr);
args = uiVaSetArgs(&nargs,
XmNarrowDirection, XmARROW_DOWN,
XmNwidth, 15,
XmNheight, 5,
XmNtopAttachment, XmATTACH_POSITION,
XmNtopPosition, 50,
XmNrightAttachment, XmATTACH_POSITION,
XmNrightPosition, 95,
XmNbottomAttachment, XmATTACH_FORM, NULL);
margindownwdg = XmCreateArrowButtonGadget(marginformwdg,
uiactiondata[callnr].ActionName,
args, nargs);
uiactiondata[callnr].Page = uiPageInfo.CurrentPage;
XtAddCallback(margindownwdg, XmNactivateCallback,
(XtCallbackProc) uiDialogActivateCB,
(caddr_t) & uiactiondata[callnr]);
UiAttachCallback(uiactiondata[callnr].ActionName, uipagesettingsmargincb,
uiactiondata[callnr].ActionName);
callnr++;
XtManageChild(margindownwdg);
args = uiVaSetArgs(&nargs,
XmNarrowDirection, XmARROW_UP,
XmNwidth, 15,
XmNheight, 5,
XmNrightAttachment, XmATTACH_POSITION,
XmNrightPosition, 95,
XmNtopAttachment, XmATTACH_FORM,
XmNbottomAttachment, XmATTACH_POSITION,
XmNbottomPosition, 50, NULL);
marginupwdg = XmCreateArrowButtonGadget(marginformwdg, "ArrowDown",
args, nargs);
uiactiondata[callnr].Page = uiPageInfo.CurrentPage;
XtAddCallback(marginupwdg, XmNactivateCallback,
(XtCallbackProc) uiDialogActivateCB,
(caddr_t) & uiactiondata[callnr]);
UiAttachCallback(uiactiondata[callnr].ActionName, uipagesettingsmargincb,
uiactiondata[callnr].ActionName);
callnr++;
XtManageChild(marginupwdg);
text = textvar[callnr / 2 - 1];
sprintf(text, "%sMargin", name);
args = uiVaSetArgs(&nargs,
XmNcolumns, 4,
XmNtopAttachment, XmATTACH_FORM,
XmNrightAttachment, XmATTACH_WIDGET,
XmNrightWidget, margindownwdg,
XmNbottomAttachment, XmATTACH_FORM, NULL);
textwdg = XmCreateText(marginformwdg, text, args, nargs);
uipstextwidget[callnr / 2 - 1] = textwdg;
XtAddCallback(textwdg, XmNactivateCallback,
(XtCallbackProc) uiDialogVariableCB, (caddr_t) text);
XtAddCallback(textwdg, XmNlosingFocusCallback,
(XtCallbackProc) uiDialogVariableCB, (caddr_t) text);
XtAddCallback(textwdg, XmNvalueChangedCallback,
(XtCallbackProc) uiDialogVariableCB, (caddr_t) text);
(void) uiAddWidgetInfo(text, textwdg, uiWTtext); /* ignore */
XtManageChild(textwdg);
return marginformwdg;
}
static Widget
uicreatepsseparator(formwdg, topwdg)
Widget formwdg;
Widget topwdg;
{
ArgList args;
Cardinal nargs;
Widget separatorwdg;
args = uiVaSetArgs(&nargs,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, topwdg,
XmNtopOffset, UI_PAGESETTINGS_WDG_OFFSET,
XmNleftAttachment, XmATTACH_FORM,
XmNrightAttachment, XmATTACH_FORM, NULL);
separatorwdg = XmCreateSeparatorGadget(formwdg, "PSSeparator",
args, nargs);
XtManageChild(separatorwdg);
return separatorwdg;
}
static Widget
uicreatepsusefixed(formwdg, topwdg)
Widget formwdg;
Widget topwdg;
{
XmString labelstr;
ArgList args;
Cardinal nargs;
Widget tmpformwdg, usefixedwdg;
Widget textwdg, usefixeddownwdg, usefixedupwdg;
static uiActionData_t actiondata[2];
labelstr = XmStringCreateSimple("Use Fixed Width");
args = uiVaSetArgs(&nargs,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, topwdg,
XmNtopOffset, UI_PAGESETTINGS_WDG_OFFSET,
XmNleftAttachment, XmATTACH_POSITION,
XmNleftPosition, 20, NULL);
tmpformwdg = XmCreateForm(formwdg, "UseFixedForm", args, nargs);
XtManageChild(tmpformwdg);
args = uiVaSetArgs(&nargs,
XmNlabelString, labelstr,
XmNtopAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_FORM,
XmNbottomAttachment, XmATTACH_FORM, NULL);
usefixedwdg = XmCreateToggleButtonGadget(tmpformwdg, "UseFixed",
args, nargs);
XtAddCallback(usefixedwdg, XmNvalueChangedCallback,
(XtCallbackProc) uiDialogVariableCB,
(caddr_t) "UseFixed");
/* Ignore */
(void) uiAddWidgetInfo("UseFixed", usefixedwdg, uiWTcheckbutton);
XtManageChild(usefixedwdg);
args = uiVaSetArgs(&nargs,
XmNcolumns, 4,
XmNtopAttachment, XmATTACH_FORM,
XmNbottomAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_WIDGET,
XmNleftWidget, usefixedwdg,
XmNleftOffset, UI_PAGESETTINGS_WDG_OFFSET, NULL);
textwdg = XmCreateText(tmpformwdg, "FixedWidth", args, nargs);
uiTopLevel.PageSettingsGfx.UseFixedTextWdg = textwdg;
XtAddCallback(textwdg, XmNactivateCallback,
(XtCallbackProc) uiDialogVariableCB,
(caddr_t) "FixedWidth");
XtAddCallback(textwdg, XmNlosingFocusCallback,
(XtCallbackProc) uiDialogVariableCB,
(caddr_t) "FixedWidth");
XtAddCallback(textwdg, XmNvalueChangedCallback,
(XtCallbackProc) uiDialogVariableCB,
(caddr_t) "FixedWidth");
/* Ignore */
(void) uiAddWidgetInfo("FixedWidth", textwdg, uiWTtext);
XtManageChild(textwdg);
args = uiVaSetArgs(&nargs,
XmNarrowDirection, XmARROW_DOWN,
XmNwidth, 15,
XmNheight, 5,
XmNbottomAttachment, XmATTACH_FORM,
XmNrightAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_WIDGET,
XmNleftWidget, textwdg,
XmNtopAttachment, XmATTACH_POSITION,
XmNtopPosition, 50, NULL);
usefixeddownwdg = XmCreateArrowButtonGadget(tmpformwdg, "UseFixedDown",
args, nargs);
actiondata[0].ActionName = "UseFixedDown";
actiondata[0].Page = uiPageInfo.CurrentPage;
XtAddCallback(usefixeddownwdg, XmNactivateCallback,
(XtCallbackProc) uiDialogActivateCB,
(caddr_t) & actiondata[0]);
UiAttachCallback("UseFixedDown", uipagesettingsusefixedcb, "UseFixedDown");
XtManageChild(usefixeddownwdg);
args = uiVaSetArgs(&nargs,
XmNarrowDirection, XmARROW_UP,
XmNwidth, 15,
XmNheight, 5,
XmNtopAttachment, XmATTACH_FORM,
XmNrightAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_WIDGET,
XmNleftWidget, textwdg,
XmNbottomAttachment, XmATTACH_POSITION,
XmNbottomPosition, 50, NULL);
usefixedupwdg = XmCreateArrowButtonGadget(tmpformwdg, "UseFixedUp",
args, nargs);
actiondata[1].ActionName = "UseFixedUp";
actiondata[1].Page = uiPageInfo.CurrentPage;
XtAddCallback(usefixedupwdg, XmNactivateCallback,
(XtCallbackProc) uiDialogActivateCB,
(caddr_t) & actiondata[1]);
UiAttachCallback("UseFixedUp", uipagesettingsusefixedcb, "UseFixedUp");
XtManageChild(usefixedupwdg);
return tmpformwdg;
}
static Widget
uicreatepssinglepage(formwdg, usefixedwdg)
Widget formwdg;
Widget usefixedwdg;
{
XmString labelstr;
ArgList args;
Cardinal nargs;
Widget singlepagewdg;
labelstr = XmStringCreateSimple("Single Page Mode");
args = uiVaSetArgs(&nargs,
XmNlabelString, labelstr,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, usefixedwdg,
XmNtopOffset, UI_PAGESETTINGS_WDG_OFFSET,
XmNleftAttachment, XmATTACH_POSITION,
XmNleftPosition, 20, NULL);
singlepagewdg = XmCreateToggleButtonGadget(formwdg, "OnePageMode",
args, nargs);
XtAddCallback(singlepagewdg, XmNvalueChangedCallback,
(XtCallbackProc) uiDialogVariableCB,
(caddr_t) "OnePageMode");
/* Ignore */
(void) uiAddWidgetInfo("OnePageMode", singlepagewdg, uiWTcheckbutton);
XtManageChild(singlepagewdg);
return singlepagewdg;
}
static void uicreatepsbuttons(formwdg, topwdg)
Widget formwdg;
Widget topwdg;
{
ArgList args;
Cardinal nargs;
Widget okwdg, applywdg, closewdg;
static uiActionData_t actiondata[3];
args = uiVaSetArgs(&nargs,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, topwdg,
XmNtopOffset, UI_PAGESETTINGS_WDG_OFFSET,
XmNleftAttachment, XmATTACH_POSITION,
XmNleftPosition, 5,
XmNrightAttachment, XmATTACH_POSITION,
XmNrightPosition, 25,
XmNbottomAttachment, XmATTACH_FORM,
XmNbottomOffset, 10, NULL);
okwdg = XmCreatePushButtonGadget(formwdg, "Ok", args, nargs);
actiondata[0].ActionName = "PSOk";
actiondata[0].Page = uiPageInfo.CurrentPage;
XtAddCallback(okwdg, XmNactivateCallback,
(XtCallbackProc) uiDialogActivateCB,
(caddr_t) & actiondata[0]);
UiAttachCallback("PSOk", uipagesettingsbuttoncb, "PSOk");
XtManageChild(okwdg);
args = uiVaSetArgs(&nargs,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, topwdg,
XmNtopOffset, UI_PAGESETTINGS_WDG_OFFSET,
XmNleftAttachment, XmATTACH_POSITION,
XmNleftPosition, 40,
XmNrightAttachment, XmATTACH_POSITION,
XmNrightPosition, 60,
XmNbottomAttachment, XmATTACH_FORM,
XmNbottomOffset, 10, NULL);
applywdg = XmCreatePushButtonGadget(formwdg, "Apply", args, nargs);
actiondata[1].ActionName = "PSApply";
actiondata[1].Page = uiPageInfo.CurrentPage;
XtAddCallback(applywdg, XmNactivateCallback,
(XtCallbackProc) uiDialogActivateCB,
(caddr_t) & actiondata[1]);
UiAttachCallback("PSApply", uipagesettingsbuttoncb, "PSApply");
XtManageChild(applywdg);
args = uiVaSetArgs(&nargs,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, topwdg,
XmNtopOffset, UI_PAGESETTINGS_WDG_OFFSET,
XmNleftAttachment, XmATTACH_POSITION,
XmNleftPosition, 75,
XmNrightAttachment, XmATTACH_POSITION,
XmNrightPosition, 95,
XmNbottomAttachment, XmATTACH_FORM,
XmNbottomOffset, 10, NULL);
closewdg = XmCreatePushButtonGadget(formwdg, "Close", args, nargs);
actiondata[2].ActionName = "PSClose";
actiondata[2].Page = uiPageInfo.CurrentPage;
XtAddCallback(closewdg, XmNactivateCallback,
(XtCallbackProc) uiDialogActivateCB,
(caddr_t) & actiondata[2]);
UiAttachCallback("PSClose", uipagesettingsbuttoncb, "PSClose");
XtManageChild(closewdg);
}
static void uipagesettingsmargincb(address, htext, htextobject, parameter)
char *address;
HText_t *htext;
HTextObject_t *htextobject;
void *parameter;
{
int i;
Widget textwdg;
char *text;
int margin;
char tmpbuffer[4];
for (i = 0; i < 8; i++)
if (!strcmp(uiactiondata[i].ActionName, (char *) parameter)) {
textwdg = uipstextwidget[i / 2];
text = XmTextGetString(textwdg);
margin = atoi(text);
if (i % 2) {
margin += 10;
if (margin > 9999)
margin = 9999;
sprintf(tmpbuffer, "%d", margin);
XmTextSetString(textwdg, tmpbuffer);
} else {
margin = (margin - 10) * (margin > 9);
sprintf(tmpbuffer, "%d", margin);
XmTextSetString(textwdg, tmpbuffer);
}
XtFree(text);
return;
}
}
static void uipagesettingsusefixedcb(address, htext, htextobject, parameter)
char *address;
HText_t *htext;
HTextObject_t *htextobject;
void *parameter;
{
Widget textwdg = uiTopLevel.PageSettingsGfx.UseFixedTextWdg;
char *fixedtext;
int width;
char tmpbuffer[4];
fixedtext = XmTextGetString(textwdg);
width = atoi(fixedtext);
if (!strcmp("UseFixedDown", (char *) parameter)) {
if (width) {
width = (width - 10) * (width > 9);
sprintf(tmpbuffer, "%d", width);
XmTextSetString(textwdg, tmpbuffer);
}
} else {
width += 10;
if (width > 9999)
width = 9999;
sprintf(tmpbuffer, "%d", width);
XmTextSetString(textwdg, tmpbuffer);
}
XtFree(fixedtext);
}
static void uipagesettingsbuttoncb(address, htext, htextobject, parameter)
char *address;
HText_t *htext;
HTextObject_t *htextobject;
void *parameter;
{
uiPage_t *page = uiPageInfo.CurrentPage;
if (!strcmp("PSOk", (char *) parameter)) {
XlClearWindow(page->Layout.Width, page->Layout.Height, page->HText);
uiPageUpdateWindow(page);
XtUnmapWidget(XtParent(uiTopLevel.PageSettingsGfx.FormWdg));
} else if (!strcmp("PSApply", (char *) parameter)) {
XlClearWindow(page->Layout.Width, page->Layout.Height,
page->HText);
uiPageUpdateWindow(page);
} else if (!strcmp("PSClose", (char *) parameter))
XtUnmapWidget(XtParent(uiTopLevel.PageSettingsGfx.FormWdg));
else /* Shouldn't reach this point */
uiDisplayWarning("psbuttoncb called with illegal parameter");
}
| C | CL | 8e8ceff5c162dd25ca7f9e9af4e8af4b90d051ba2fc70ff30c47a57e3f26f049 |
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma region HEAD
#pragma region DESCRIPTION
/* using light SDL2 template: https://github.com/Acry/SDL2-C-KDev_App_Template_light
* DeCasteljau Subdivision
* cubic bezier curves
* http://www.cubic.org/docs/bezier.htm
*/
/* DEFINED PROGRESS GOALS
* connect 4 points with 3 lines
*
*/
#pragma endregion DESCRIPTION
#pragma region INCLUDES
//system headers
#include <math.h>
//local headers
#include "helper.h"
//external headers
#include <SDL2/SDL2_gfxPrimitives.h>
#pragma endregion INCLUDES
#pragma region CPP DEFINITIONS
#define WHITE 255, 255, 255, 255
#define BLACK 0, 0, 0, 255
#define RED 255, 0, 0, 255
#define WW 550
#define WH (WW / 16) * 12
#define POINTS 4
#define RADIUS 4
#pragma endregion CPP DEFINITIONS
#pragma region DATASTRUCTURES
SDL_Point points[POINTS];
struct fpoint
{
float x;
float y;
};
void round_points(SDL_Point *, struct fpoint *);
void lerp(struct fpoint *, struct fpoint *, struct fpoint *, float);
void bezier(struct fpoint *, struct fpoint *,
struct fpoint *, struct fpoint *, struct fpoint *, float);
SDL_bool PointInCircle(SDL_Point *, SDL_Point *, int);
#pragma endregion DATASTRUCTURES
#pragma region GLOBALS
int ww = WW;
int wh = WH;
#pragma region VISIBLES
SDL_Surface *temp_surface = NULL;
SDL_Texture *logo = NULL;
SDL_Rect logo_dst;
#pragma endregion VISIBLES
SDL_Point mouse;
SDL_bool mouse_follow = SDL_FALSE;
SDL_Point mouse_offset;
int selected_circle = -1;
#pragma endregion GLOBALS
#pragma region FUNCTION PROTOTYPES
void assets_in(void);
void assets_out(void);
#pragma endregion FUNCTION PROTOTYPES
#pragma endregion HEAD
#pragma region MAIN FUNCTION
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
#pragma region INIT
init();
assets_in();
#pragma region WINDOW
SDL_SetWindowPosition(Window, 0, 0);
SDL_SetWindowSize(Window, ww, wh);
SDL_SetWindowTitle(Window, "cubic beziers à la casteljau");
SDL_ShowWindow(Window);
#pragma endregion WINDOW
points[0].x = 40;
points[0].y = WH / 2;
points[1].x = 142;
points[1].y = 55;
points[2].x = 372;
points[2].y = 334;
points[3].x = WW - 40;
points[3].y = 160;
struct fpoint fpoints[4];
for (int i = 0; i < POINTS; i++)
{
round_points(&points[i], &fpoints[i]);
}
SDL_Event event;
int running = 1;
#pragma endregion INIT
#pragma region MAIN LOOP
while (running)
{
#pragma region EVENT LOOP
SDL_GetMouseState(&mouse.x, &mouse.y);
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
running = 0;
}
if (event.type == SDL_MOUSEMOTION)
{
// SDL_Log("x:%d y:%d",mouse.x, mouse.y);
}
if (event.type == SDL_MOUSEBUTTONDOWN)
{
if (event.button.button == SDL_BUTTON_RIGHT)
{
;
}
if (event.button.button == SDL_BUTTON_MIDDLE)
{
;
}
if (event.button.button == SDL_BUTTON_LEFT && !mouse_follow)
{
for (int i = 0; i < POINTS; i++)
{
if (PointInCircle(&mouse, &points[i], RADIUS))
{
SDL_Log("mouse in circle");
mouse_follow = SDL_TRUE;
selected_circle = i;
}
}
}
}
if (mouse_follow && event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT)
{
mouse_follow = SDL_FALSE;
selected_circle = -1;
}
if (event.type == SDL_KEYDOWN)
{
switch (event.key.keysym.sym)
{
case SDLK_ESCAPE:
running = 0;
break;
default:
break;
}
}
}
#pragma endregion EVENT LOOP
#pragma region RENDERING
SDL_SetRenderDrawColor(Renderer, WHITE);
SDL_RenderClear(Renderer);
SDL_RenderCopy(Renderer, logo, NULL, &logo_dst);
// Move Control-Points
if (mouse_follow)
{
points[selected_circle].x = mouse.x - mouse_offset.x;
points[selected_circle].y = mouse.y - mouse_offset.y;
round_points(&points[selected_circle], &fpoints[selected_circle]);
}
// Draw Control-Points
for (int i = 0; i < POINTS; i++)
{
aacircleRGBA(Renderer, points[i].x, points[i].y, RADIUS, RED);
if (i < POINTS - 1)
aalineRGBA(Renderer, points[i].x, points[i].y,
points[i + 1].x, points[i + 1].y, RED);
}
// Draw Curve
SDL_SetRenderDrawColor(Renderer, BLACK);
for (int i = 0; i < 1000; ++i)
{
struct fpoint pp;
float t = ((float)i / 999.0);
bezier(&pp, &fpoints[0], &fpoints[1], &fpoints[2], &fpoints[3], t);
SDL_RenderDrawPoint(Renderer, roundf(pp.x), roundf(pp.y));
}
SDL_RenderPresent(Renderer);
#pragma endregion RENDERING
}
#pragma endregion MAIN LOOP
assets_out();
exit_();
return EXIT_SUCCESS;
}
#pragma endregion MAIN FUNCTION
#pragma region FUNCTIONS
void assets_in(void)
{
#pragma region LOGO
temp_surface = IMG_Load("./assets/gfx/logo.png");
logo = SDL_CreateTextureFromSurface(Renderer, temp_surface);
SDL_QueryTexture(logo, NULL, NULL, &logo_dst.w, &logo_dst.h);
SDL_SetTextureAlphaMod(logo, 100);
logo_dst.x = (ww / 2) - (logo_dst.w / 2);
logo_dst.y = (wh / 2) - (logo_dst.h / 2);
#pragma endregion LOGO
}
void assets_out(void)
{
SDL_DestroyTexture(logo);
}
void bezier(struct fpoint *dest, struct fpoint *a, struct fpoint *b, struct fpoint *c, struct fpoint *d, float t)
{
struct fpoint ab, bc, cd, abbc, bccd;
lerp(&ab, a, b, t); // point between a and b (green)
lerp(&bc, b, c, t); // point between b and c (green)
lerp(&cd, c, d, t); // point between c and d (green)
lerp(&abbc, &ab, &bc, t); // point between ab and bc (blue)
lerp(&bccd, &bc, &cd, t); // point between bc and cd (blue)
lerp(dest, &abbc, &bccd, t); // point on the bezier-curve (black)
}
// simple linear interpolation between two points
void lerp(struct fpoint *dest, struct fpoint *a, struct fpoint *b, float t)
{
dest->x = a->x + (b->x - a->x) * t;
dest->y = a->y + (b->y - a->y) * t;
}
void round_points(SDL_Point *ipoint, struct fpoint *fpoint)
{
fpoint->x = roundf(ipoint->x);
fpoint->y = roundf(ipoint->y);
}
SDL_bool PointInCircle(SDL_Point *point, SDL_Point *center, int radius)
{
float x = center->x;
float y = center->y;
float r = (float)radius;
float dx = x - point->x;
float dy = y - point->y;
float distance = sqrtf(dx * dx + dy * dy);
if (distance < r + 1)
return SDL_TRUE;
return SDL_FALSE;
}
#pragma endregion FUNCTIONS
| C | CL | 23315803290cfb3b4892f0e126324637582d2e1f4af49e5945b3981adec1110d |
/*
* Dynamic Data exchange library [libdy]
* Copyright (C) 2015 Taeyeon Mori
*
* 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/>.
*/
/**
* @file libdy/exceptions_c.h
* @brief Helper macros for working with libdy exceptions from C
*/
#pragma once
#include "exceptions.h"
#include <assert.h>
/// Ensure a exception is set when returning an error
#define dy_return_error(T) { \
assert(DyErr_Occurred() && "return_error: error return without exception set."); \
return T; \
}
#define dy_return_null dy_return_error(NULL)
/// Exception propagation macro
#define dy_propagate_error(retval) \
{ if (DyErr_Occurred()) return retval; }
#define dy_propagate_null() \
dy_propagate_error(NULL)
/** @{
* @name Error handler macros
*
* Usage:
* @code
* fn_call()
* DY_ERR_HANDLER
* DY_ERR_CATCH("libdy.SomeError", e)
* do_something(e);
* DY_ERR_CATCH_ALL(e)
* {
* print_error(e);
* DY_ERR_RETHROW();
* }
* DY_ERR_HANDLER_END
* @endcode
*
* @warning do NOT escape a DY_ERR_HANDLER block using flow control!
* You can use "DY_ERR_RETURN(x);" instead of "return x;" or
* "DY_ERR_RETHROW_RETURN(e);" instead of "DY_ERR_RETHROW(); return e;"
* for others, you can prefix them with DY_ERR_ESCAPE: "DY_ERR_ESCAPE break;"
*/
/// Begin a libdy error handler
#define DY_ERR_HANDLER \
{ \
DyObject *__exception = DyErr_Occurred(); \
if (__exception) \
{ \
bool __ehandled = false, __edone = false; \
{
/// Begin a catch clause
/// @sa DyErr_Filter for information on errid
#define DY_ERR_CATCH(errid, var) \
} \
if (!__edone) { \
DyObject *var = __exception; \
__ehandled = __edone = DyErr_Filter(var, errid); \
if (__edone)
/// Begin a catch-all clause
#define DY_ERR_CATCH_ALL(var) \
} \
if (!__edone) { \
DyObject *var = __exception; \
__ehandled = __edone = true;
/// Allows to escape the error handler
#define DY_ERR_ESCAPE \
if (__ehandled) \
DyErr_Clear();
/// Return from the function executing the error handler
/// Same as \code DY_ERR_ESCAPE return val; \endcode
#define DY_ERR_RETURN(val) \
DY_ERR_ESCAPE return val
/// Rethrow the exception when the handler is left
#define DY_ERR_RETHROW() \
__ehandled = false;
/// Rethrow the exception and return from the executing function
#define DY_ERR_RETHROW_RETURN(val) \
return val;
/// Leave a libdy error handler
#define DY_ERR_HANDLER_END \
} \
DY_ERR_ESCAPE \
} \
}
///@} | C | CL | a5ab58f1a92834ef5ab5ed540e6f653292dd55c88dff013c2a8dab27065f9c5d |
#ifndef SS_RENDER_PASS_I
#define SS_RENDER_PASS_I
#include <gs/gs.h>
#define _base(base_type) base_type _base
// Abstract interface for all render passes passes
typedef struct render_pass_i {
void (* pass)(gs_command_buffer_t* cb, struct render_pass_i* pass, void* paramters);
} render_pass_i;
#endif | C | CL | 11f001499f194a075ebd4773f842ec6f1c9cba21f75807d651a9c350e85127e4 |
/*
** EPITECH PROJECT, 2021
** zappy_linked
** File description:
** internal functions
*/
#include <time.h>
#include <stdio.h>
#include "zappy_server_structs.h"
/**
* update the timer by increasing last "checkpoint" by delta time
* @param timer struct containing every needed information:
* last_checkpoint.sec last_checkpoint.nsec and delta(nanoseconds)
*/
static void update_timer(zappy_timer_t *timer)
{
if (timer->nano_seconds + timer->delta_size >= 1000000000) {
timer->nano_seconds =
(timer->nano_seconds + timer->delta_size) % 1000000000;
timer->seconds += 1;
} else {
timer->nano_seconds += timer->delta_size;
}
}
/**
* checks if delta time has elapsed
* @param timer the struct containing time information,
* it is updated if the condition is true
* @return 1 if time was elapsed, 0 otherwise
*/
int is_elapsed_time(zappy_timer_t *timer)
{
struct timespec time;
clock_gettime(CLOCK_MONOTONIC_RAW, &time);
if (time.tv_sec != timer->seconds ||
time.tv_nsec - timer->delta_size >= timer->nano_seconds) {
update_timer(timer);
return 1;
}
return 0;
}
| C | CL | 4ca4bff9ba324b97a79dca0261dcd5a1bf2dfd4dbd73e0051af57cdf12fce8f6 |
//
// shoes/http/winhttp.c
// the central download routine
// (isolated so it can be reused in platform/msw/stub.c)
//
#include "shoes/app.h"
#include "shoes/ruby.h"
#include "shoes/internal.h"
#include "shoes/config.h"
#include "shoes/version.h"
#include "shoes/http/common.h"
#include "shoes/http/winhttp.h"
void shoes_get_time(SHOES_TIME *ts)
{
*ts = GetTickCount();
}
unsigned long shoes_diff_time(SHOES_TIME *start, SHOES_TIME *end)
{
return *end - *start;
}
void
shoes_winhttp_headers(HINTERNET req, shoes_http_handler handler, void *data)
{
DWORD size;
WinHttpQueryHeaders(req, WINHTTP_QUERY_RAW_HEADERS,
WINHTTP_HEADER_NAME_BY_INDEX, NULL, &size, WINHTTP_NO_HEADER_INDEX);
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
int whdrlen = 0, hdrlen = 0;
LPCWSTR whdr;
LPSTR hdr = SHOE_ALLOC_N(CHAR, MAX_PATH);
LPCWSTR hdrs = SHOE_ALLOC_N(WCHAR, size/sizeof(WCHAR));
BOOL res = WinHttpQueryHeaders(req, WINHTTP_QUERY_RAW_HEADERS,
WINHTTP_HEADER_NAME_BY_INDEX, (LPVOID)hdrs, &size, WINHTTP_NO_HEADER_INDEX);
if (res)
{
for (whdr = hdrs; whdr - hdrs < size / sizeof(WCHAR); whdr += whdrlen)
{
WideCharToMultiByte(CP_UTF8, 0, whdr, -1, hdr, MAX_PATH, NULL, NULL);
hdrlen = strlen(hdr);
HTTP_HEADER(hdr, hdrlen, handler, data);
whdrlen = wcslen(whdr) + 1;
}
}
SHOE_FREE(hdrs);
SHOE_FREE(hdr);
}
}
void
shoes_winhttp(LPCWSTR scheme, LPCWSTR host, INTERNET_PORT port, LPCWSTR path, LPCWSTR method,
LPCWSTR headers, LPVOID body, DWORD bodylen, TCHAR **mem, ULONG memlen, HANDLE file,
LPDWORD size, UCHAR flags, shoes_http_handler handler, void *data)
{
LPWSTR proxy;
DWORD len = 0, rlen = 0, status = 0, complete = 0, flen = 0, total = 0, written = 0;
LPTSTR buf = SHOE_ALLOC_N(TCHAR, SHOES_BUFSIZE);
LPTSTR fbuf = SHOE_ALLOC_N(TCHAR, SHOES_CHUNKSIZE);
LPWSTR uagent = SHOE_ALLOC_N(WCHAR, SHOES_BUFSIZE);
HINTERNET sess = NULL, conn = NULL, req = NULL;
SHOES_TIME last = 0;
if (buf == NULL || fbuf == NULL || uagent == NULL)
goto done;
_snwprintf(uagent, SHOES_BUFSIZE, L"Shoes/0.r%d (%S) %S/%d", SHOES_REVISION, SHOES_PLATFORM,
SHOES_RELEASE_NAME, SHOES_BUILD_DATE);
sess = WinHttpOpen(uagent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (sess == NULL)
goto done;
conn = WinHttpConnect(sess, host, port, 0);
if (conn == NULL)
goto done;
if (method == NULL) method = L"GET";
req = WinHttpOpenRequest(conn, method, path,
NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (req == NULL)
goto done;
proxy = _wgetenv(L"http_proxy");
if (proxy != NULL)
{
WINHTTP_PROXY_INFO proxy_info;
proxy_info.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
proxy_info.lpszProxy = proxy;
proxy_info.lpszProxyBypass = NULL;
WinHttpSetOption(req, WINHTTP_OPTION_PROXY, &proxy_info, sizeof(proxy_info));
}
if (!(flags & SHOES_DL_REDIRECTS))
{
DWORD options = WINHTTP_DISABLE_REDIRECTS;
WinHttpSetOption(req, WINHTTP_OPTION_DISABLE_FEATURE, &options, sizeof(options));
}
if (headers != NULL)
WinHttpAddRequestHeaders(req, headers, -1L, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
if (!WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0,
(LPVOID)body, bodylen, bodylen, 0))
goto done;
if (!WinHttpReceiveResponse(req, NULL))
goto done;
len = sizeof(DWORD);
if (!WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
NULL, &status, &len, NULL))
goto done;
else if (handler != NULL)
{
shoes_http_event *event = SHOE_ALLOC(shoes_http_event);
SHOE_MEMZERO(event, shoes_http_event, 1);
event->stage = SHOES_HTTP_STATUS;
event->status = status;
handler(event, data);
SHOE_FREE(event);
}
if (handler != NULL) shoes_winhttp_headers(req, handler, data);
*size = 0;
len = sizeof(buf);
if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_LENGTH | WINHTTP_QUERY_FLAG_NUMBER,
NULL, size, &len, NULL))
{
if (*mem != NULL && *size > memlen)
{
SHOE_REALLOC_N(*mem, char, (memlen = *size));
if (*mem == NULL) goto done;
}
}
HTTP_EVENT(handler, SHOES_HTTP_CONNECTED, last, 0, 0, *size, data, NULL, goto done);
total = *size * 100;
rlen = *size;
while (1)
{
len = 0;
WinHttpReadData(req, fbuf, SHOES_CHUNKSIZE, &len);
if (len <= 0)
break;
if (*mem != NULL)
{
if (written + len > memlen)
{
while (written + len > memlen)
memlen += SHOES_BUFSIZE;
SHOE_REALLOC_N(*mem, char, memlen);
if (*mem == NULL) goto done;
}
SHOE_MEMCPY(*mem + written, fbuf, char, len);
}
if (file != INVALID_HANDLE_VALUE)
WriteFile(file, (LPBYTE)fbuf, len, &flen, NULL);
written += len;
if (*size == 0) total = written * 100;
if (total > 0)
{
HTTP_EVENT(handler, SHOES_HTTP_TRANSFER, last, (int)((total - (rlen * 100)) / (total / 100)),
(total / 100) - rlen, (total / 100), data, NULL, break);
}
if (rlen > len) rlen -= len;
}
*size = written;
if (file != INVALID_HANDLE_VALUE)
{
CloseHandle(file);
file = INVALID_HANDLE_VALUE;
}
HTTP_EVENT(handler, SHOES_HTTP_COMPLETED, last, 100, *size, *size, data, *mem, goto done);
complete = 1;
done:
if (buf != NULL) SHOE_FREE(buf);
if (fbuf != NULL) SHOE_FREE(fbuf);
if (uagent != NULL) SHOE_FREE(uagent);
if (!complete)
{
shoes_http_event *event = SHOE_ALLOC(shoes_http_event);
SHOE_MEMZERO(event, shoes_http_event, 1);
event->stage = SHOES_HTTP_ERROR;
event->error = GetLastError();
int hx = handler(event, data);
SHOE_FREE(event);
if (hx & SHOES_DOWNLOAD_HALT) goto done;
}
if (file != INVALID_HANDLE_VALUE)
CloseHandle(file);
if (req)
WinHttpCloseHandle(req);
if (conn)
WinHttpCloseHandle(conn);
if (sess)
WinHttpCloseHandle(sess);
}
| C | CL | 3ec2a7a0af048e1695eb75141028f17ea77adf08a342c1211a8c8fd017011d1a |
#include <petsc/private/vecimpl.h>
#define DEFAULT_STASH_SIZE 100
/*
VecStashCreate_Private - Creates a stash,currently used for all the parallel
matrix implementations. The stash is where elements of a matrix destined
to be stored on other processors are kept until matrix assembly is done.
This is a simple minded stash. Simply adds entries to end of stash.
Input Parameters:
comm - communicator, required for scatters.
bs - stash block size. used when stashing blocks of values
Output Parameter:
. stash - the newly created stash
*/
PetscErrorCode VecStashCreate_Private(MPI_Comm comm, PetscInt bs, VecStash *stash)
{
PetscInt max, *opt, nopt;
PetscBool flg;
PetscFunctionBegin;
/* Require 2 tags, get the second using PetscCommGetNewTag() */
stash->comm = comm;
PetscCall(PetscCommGetNewTag(stash->comm, &stash->tag1));
PetscCall(PetscCommGetNewTag(stash->comm, &stash->tag2));
PetscCallMPI(MPI_Comm_size(stash->comm, &stash->size));
PetscCallMPI(MPI_Comm_rank(stash->comm, &stash->rank));
nopt = stash->size;
PetscCall(PetscMalloc1(nopt, &opt));
PetscCall(PetscOptionsGetIntArray(NULL, NULL, "-vecstash_initial_size", opt, &nopt, &flg));
if (flg) {
if (nopt == 1) max = opt[0];
else if (nopt == stash->size) max = opt[stash->rank];
else if (stash->rank < nopt) max = opt[stash->rank];
else max = 0; /* use default */
stash->umax = max;
} else {
stash->umax = 0;
}
PetscCall(PetscFree(opt));
if (bs <= 0) bs = 1;
stash->bs = bs;
stash->nmax = 0;
stash->oldnmax = 0;
stash->n = 0;
stash->reallocs = -1;
stash->idx = NULL;
stash->array = NULL;
stash->send_waits = NULL;
stash->recv_waits = NULL;
stash->send_status = NULL;
stash->nsends = 0;
stash->nrecvs = 0;
stash->svalues = NULL;
stash->rvalues = NULL;
stash->rmax = 0;
stash->nprocs = NULL;
stash->nprocessed = 0;
stash->donotstash = PETSC_FALSE;
stash->ignorenegidx = PETSC_FALSE;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*
VecStashDestroy_Private - Destroy the stash
*/
PetscErrorCode VecStashDestroy_Private(VecStash *stash)
{
PetscFunctionBegin;
PetscCall(PetscFree2(stash->array, stash->idx));
PetscCall(PetscFree(stash->bowners));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*
VecStashScatterEnd_Private - This is called as the final stage of
scatter. The final stages of message passing is done here, and
all the memory used for message passing is cleanedu up. This
routine also resets the stash, and deallocates the memory used
for the stash. It also keeps track of the current memory usage
so that the same value can be used the next time through.
*/
PetscErrorCode VecStashScatterEnd_Private(VecStash *stash)
{
PetscInt nsends = stash->nsends, oldnmax;
MPI_Status *send_status;
PetscFunctionBegin;
/* wait on sends */
if (nsends) {
PetscCall(PetscMalloc1(2 * nsends, &send_status));
PetscCallMPI(MPI_Waitall(2 * nsends, stash->send_waits, send_status));
PetscCall(PetscFree(send_status));
}
/* Now update nmaxold to be app 10% more than max n, this way the
wastage of space is reduced the next time this stash is used.
Also update the oldmax, only if it increases */
if (stash->n) {
oldnmax = ((PetscInt)(stash->n * 1.1) + 5) * stash->bs;
if (oldnmax > stash->oldnmax) stash->oldnmax = oldnmax;
}
stash->nmax = 0;
stash->n = 0;
stash->reallocs = -1;
stash->rmax = 0;
stash->nprocessed = 0;
PetscCall(PetscFree2(stash->array, stash->idx));
stash->array = NULL;
stash->idx = NULL;
PetscCall(PetscFree(stash->send_waits));
PetscCall(PetscFree(stash->recv_waits));
PetscCall(PetscFree2(stash->svalues, stash->sindices));
PetscCall(PetscFree2(stash->rvalues, stash->rindices));
PetscCall(PetscFree(stash->nprocs));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*
VecStashGetInfo_Private - Gets the relevant statistics of the stash
Input Parameters:
stash - the stash
nstash - the size of the stash
reallocs - the number of additional mallocs incurred.
*/
PetscErrorCode VecStashGetInfo_Private(VecStash *stash, PetscInt *nstash, PetscInt *reallocs)
{
PetscFunctionBegin;
if (nstash) *nstash = stash->n * stash->bs;
if (reallocs) {
if (stash->reallocs < 0) *reallocs = 0;
else *reallocs = stash->reallocs;
}
PetscFunctionReturn(PETSC_SUCCESS);
}
/*
VecStashSetInitialSize_Private - Sets the initial size of the stash
Input Parameters:
stash - the stash
max - the value that is used as the max size of the stash.
this value is used while allocating memory. It specifies
the number of vals stored, even with the block-stash
*/
PetscErrorCode VecStashSetInitialSize_Private(VecStash *stash, PetscInt max)
{
PetscFunctionBegin;
stash->umax = max;
PetscFunctionReturn(PETSC_SUCCESS);
}
/* VecStashExpand_Private - Expand the stash. This function is called
when the space in the stash is not sufficient to add the new values
being inserted into the stash.
Input Parameters:
stash - the stash
incr - the minimum increase requested
Notes:
This routine doubles the currently used memory.
*/
PetscErrorCode VecStashExpand_Private(VecStash *stash, PetscInt incr)
{
PetscInt *n_idx, newnmax, bs = stash->bs;
PetscScalar *n_array;
PetscFunctionBegin;
/* allocate a larger stash. */
if (!stash->oldnmax && !stash->nmax) { /* new stash */
if (stash->umax) newnmax = stash->umax / bs;
else newnmax = DEFAULT_STASH_SIZE / bs;
} else if (!stash->nmax) { /* resuing stash */
if (stash->umax > stash->oldnmax) newnmax = stash->umax / bs;
else newnmax = stash->oldnmax / bs;
} else newnmax = stash->nmax * 2;
if (newnmax < (stash->nmax + incr)) newnmax += 2 * incr;
PetscCall(PetscMalloc2(bs * newnmax, &n_array, newnmax, &n_idx));
PetscCall(PetscMemcpy(n_array, stash->array, bs * stash->nmax * sizeof(PetscScalar)));
PetscCall(PetscMemcpy(n_idx, stash->idx, stash->nmax * sizeof(PetscInt)));
PetscCall(PetscFree2(stash->array, stash->idx));
stash->array = n_array;
stash->idx = n_idx;
stash->nmax = newnmax;
stash->reallocs++;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*
VecStashScatterBegin_Private - Initiates the transfer of values to the
correct owners. This function goes through the stash, and check the
owners of each stashed value, and sends the values off to the owner
processors.
Input Parameters:
stash - the stash
owners - an array of size 'no-of-procs' which gives the ownership range
for each node.
Notes:
The 'owners' array in the cased of the blocked-stash has the
ranges specified blocked global indices, and for the regular stash in
the proper global indices.
*/
PetscErrorCode VecStashScatterBegin_Private(VecStash *stash, const PetscInt *owners)
{
PetscMPIInt size = stash->size, tag1 = stash->tag1, tag2 = stash->tag2;
PetscInt *owner, *start, *nprocs, nsends, nreceives;
PetscInt nmax, count, *sindices, *rindices, i, j, idx, bs = stash->bs, lastidx;
PetscScalar *rvalues, *svalues;
MPI_Comm comm = stash->comm;
MPI_Request *send_waits, *recv_waits;
PetscFunctionBegin;
/* first count number of contributors to each processor */
PetscCall(PetscCalloc1(2 * size, &nprocs));
PetscCall(PetscMalloc1(stash->n, &owner));
j = 0;
lastidx = -1;
for (i = 0; i < stash->n; i++) {
/* if indices are NOT locally sorted, need to start search at the beginning */
if (lastidx > (idx = stash->idx[i])) j = 0;
lastidx = idx;
for (; j < size; j++) {
if (idx >= owners[j] && idx < owners[j + 1]) {
nprocs[2 * j]++;
nprocs[2 * j + 1] = 1;
owner[i] = j;
break;
}
}
}
nsends = 0;
for (i = 0; i < size; i++) nsends += nprocs[2 * i + 1];
/* inform other processors of number of messages and max length*/
PetscCall(PetscMaxSum(comm, nprocs, &nmax, &nreceives));
/* post receives:
since we don't know how long each individual message is we
allocate the largest needed buffer for each receive. Potentially
this is a lot of wasted space.
*/
PetscCall(PetscMalloc2(nreceives * nmax * bs, &rvalues, nreceives * nmax, &rindices));
PetscCall(PetscMalloc1(2 * nreceives, &recv_waits));
for (i = 0, count = 0; i < nreceives; i++) {
PetscCallMPI(MPI_Irecv(rvalues + bs * nmax * i, bs * nmax, MPIU_SCALAR, MPI_ANY_SOURCE, tag1, comm, recv_waits + count++));
PetscCallMPI(MPI_Irecv(rindices + nmax * i, nmax, MPIU_INT, MPI_ANY_SOURCE, tag2, comm, recv_waits + count++));
}
/* do sends:
1) starts[i] gives the starting index in svalues for stuff going to
the ith processor
*/
PetscCall(PetscMalloc2(stash->n * bs, &svalues, stash->n, &sindices));
PetscCall(PetscMalloc1(2 * nsends, &send_waits));
PetscCall(PetscMalloc1(size, &start));
/* use 2 sends the first with all_v, the next with all_i */
start[0] = 0;
for (i = 1; i < size; i++) start[i] = start[i - 1] + nprocs[2 * i - 2];
for (i = 0; i < stash->n; i++) {
j = owner[i];
if (bs == 1) svalues[start[j]] = stash->array[i];
else PetscCall(PetscMemcpy(svalues + bs * start[j], stash->array + bs * i, bs * sizeof(PetscScalar)));
sindices[start[j]] = stash->idx[i];
start[j]++;
}
start[0] = 0;
for (i = 1; i < size; i++) start[i] = start[i - 1] + nprocs[2 * i - 2];
for (i = 0, count = 0; i < size; i++) {
if (nprocs[2 * i + 1]) {
PetscCallMPI(MPI_Isend(svalues + bs * start[i], bs * nprocs[2 * i], MPIU_SCALAR, i, tag1, comm, send_waits + count++));
PetscCallMPI(MPI_Isend(sindices + start[i], nprocs[2 * i], MPIU_INT, i, tag2, comm, send_waits + count++));
}
}
PetscCall(PetscFree(owner));
PetscCall(PetscFree(start));
/* This memory is reused in scatter end for a different purpose*/
for (i = 0; i < 2 * size; i++) nprocs[i] = -1;
stash->nprocs = nprocs;
stash->svalues = svalues;
stash->sindices = sindices;
stash->rvalues = rvalues;
stash->rindices = rindices;
stash->nsends = nsends;
stash->nrecvs = nreceives;
stash->send_waits = send_waits;
stash->recv_waits = recv_waits;
stash->rmax = nmax;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*
VecStashScatterGetMesg_Private - This function waits on the receives posted
in the function VecStashScatterBegin_Private() and returns one message at
a time to the calling function. If no messages are left, it indicates this
by setting flg = 0, else it sets flg = 1.
Input Parameters:
stash - the stash
Output Parameters:
nvals - the number of entries in the current message.
rows - an array of row indices (or blocked indices) corresponding to the values
cols - an array of columnindices (or blocked indices) corresponding to the values
vals - the values
flg - 0 indicates no more message left, and the current call has no values associated.
1 indicates that the current call successfully received a message, and the
other output parameters nvals,rows,cols,vals are set appropriately.
*/
PetscErrorCode VecStashScatterGetMesg_Private(VecStash *stash, PetscMPIInt *nvals, PetscInt **rows, PetscScalar **vals, PetscInt *flg)
{
PetscMPIInt i = 0; /* dummy value so MPI-Uni doesn't think it is not set */
PetscInt *flg_v;
PetscInt i1, i2, bs = stash->bs;
MPI_Status recv_status;
PetscBool match_found = PETSC_FALSE;
PetscFunctionBegin;
*flg = 0; /* When a message is discovered this is reset to 1 */
/* Return if no more messages to process */
if (stash->nprocessed == stash->nrecvs) PetscFunctionReturn(PETSC_SUCCESS);
flg_v = stash->nprocs;
/* If a matching pair of receives are found, process them, and return the data to
the calling function. Until then keep receiving messages */
while (!match_found) {
PetscCallMPI(MPI_Waitany(2 * stash->nrecvs, stash->recv_waits, &i, &recv_status));
/* Now pack the received message into a structure which is useable by others */
if (i % 2) {
PetscCallMPI(MPI_Get_count(&recv_status, MPIU_INT, nvals));
flg_v[2 * recv_status.MPI_SOURCE + 1] = i / 2;
} else {
PetscCallMPI(MPI_Get_count(&recv_status, MPIU_SCALAR, nvals));
flg_v[2 * recv_status.MPI_SOURCE] = i / 2;
*nvals = *nvals / bs;
}
/* Check if we have both the messages from this proc */
i1 = flg_v[2 * recv_status.MPI_SOURCE];
i2 = flg_v[2 * recv_status.MPI_SOURCE + 1];
if (i1 != -1 && i2 != -1) {
*rows = stash->rindices + i2 * stash->rmax;
*vals = stash->rvalues + i1 * bs * stash->rmax;
*flg = 1;
stash->nprocessed++;
match_found = PETSC_TRUE;
}
}
PetscFunctionReturn(PETSC_SUCCESS);
}
/*
* Sort the stash, removing duplicates (combining as appropriate).
*/
PetscErrorCode VecStashSortCompress_Private(VecStash *stash)
{
PetscInt i, j, bs = stash->bs;
PetscFunctionBegin;
if (!stash->n) PetscFunctionReturn(PETSC_SUCCESS);
if (bs == 1) {
PetscCall(PetscSortIntWithScalarArray(stash->n, stash->idx, stash->array));
for (i = 1, j = 0; i < stash->n; i++) {
if (stash->idx[i] == stash->idx[j]) {
switch (stash->insertmode) {
case ADD_VALUES:
stash->array[j] += stash->array[i];
break;
case INSERT_VALUES:
stash->array[j] = stash->array[i];
break;
default:
SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Insert mode not supported 0x%x", stash->insertmode);
}
} else {
j++;
stash->idx[j] = stash->idx[i];
stash->array[j] = stash->array[i];
}
}
stash->n = j + 1;
} else { /* block stash */
PetscInt *perm = NULL;
PetscScalar *arr;
PetscCall(PetscMalloc2(stash->n, &perm, stash->n * bs, &arr));
for (i = 0; i < stash->n; i++) perm[i] = i;
PetscCall(PetscSortIntWithArray(stash->n, stash->idx, perm));
/* Out-of-place copy of arr */
PetscCall(PetscMemcpy(arr, stash->array + perm[0] * bs, bs * sizeof(PetscScalar)));
for (i = 1, j = 0; i < stash->n; i++) {
PetscInt k;
if (stash->idx[i] == stash->idx[j]) {
switch (stash->insertmode) {
case ADD_VALUES:
for (k = 0; k < bs; k++) arr[j * bs + k] += stash->array[perm[i] * bs + k];
break;
case INSERT_VALUES:
for (k = 0; k < bs; k++) arr[j * bs + k] = stash->array[perm[i] * bs + k];
break;
default:
SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Insert mode not supported 0x%x", stash->insertmode);
}
} else {
j++;
stash->idx[j] = stash->idx[i];
for (k = 0; k < bs; k++) arr[j * bs + k] = stash->array[perm[i] * bs + k];
}
}
stash->n = j + 1;
PetscCall(PetscMemcpy(stash->array, arr, stash->n * bs * sizeof(PetscScalar)));
PetscCall(PetscFree2(perm, arr));
}
PetscFunctionReturn(PETSC_SUCCESS);
}
PetscErrorCode VecStashGetOwnerList_Private(VecStash *stash, PetscLayout map, PetscMPIInt *nowners, PetscMPIInt **owners)
{
PetscInt i, bs = stash->bs;
PetscMPIInt r;
PetscSegBuffer seg;
PetscFunctionBegin;
PetscCheck(bs == 1 || bs == map->bs, map->comm, PETSC_ERR_PLIB, "Stash block size %" PetscInt_FMT " does not match layout block size %" PetscInt_FMT, bs, map->bs);
PetscCall(PetscSegBufferCreate(sizeof(PetscMPIInt), 50, &seg));
*nowners = 0;
for (i = 0, r = -1; i < stash->n; i++) {
if (stash->idx[i] * bs >= map->range[r + 1]) {
PetscMPIInt *rank;
PetscCall(PetscSegBufferGet(seg, 1, &rank));
PetscCall(PetscLayoutFindOwner(map, stash->idx[i] * bs, &r));
*rank = r;
(*nowners)++;
}
}
PetscCall(PetscSegBufferExtractAlloc(seg, owners));
PetscCall(PetscSegBufferDestroy(&seg));
PetscFunctionReturn(PETSC_SUCCESS);
}
| C | CL | e5ef91a529a84962d7ed023a9f3234467b0e3b296d5a898c61a01de62af84eeb |
/****************************************************************
* aoctree.c:
****************************************************************/
/******
Copyright (C) 1995 by Klaus Ehrenfried.
Permission to use, copy, modify, and distribute this software
is hereby granted, provided that the above copyright notice appears
in all copies and that the software is available to all free of charge.
The author disclaims all warranties with regard to this software,
including all implied warranties of merchant-ability and fitness.
The code is simply distributed as it is.
*******/
/*******
This program is based on the Octree algorithm described
by Michael Gervautz and Werner Purgathofer (Technical University
Vienna, Austria) in the article "A Simple Method for Color Quantization:
Octree Quantization" published in Graphic Gems edited by Andrew Glassner
pp. 287 ff.
*******/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "apro.h"
#define BIGVAL 0x10000000
typedef struct node *OCTREE;
struct node
{
UBYTE leaf;
UBYTE level;
UBYTE color;
UBYTE rgb[3];
UBYTE sub_count;
ULONG pixels_low;
ULONG pixels_high;
ULONG red_sum_low;
ULONG red_sum_high;
ULONG green_sum_low;
ULONG green_sum_high;
ULONG blue_sum_low;
ULONG blue_sum_high;
OCTREE sub[8];
OCTREE next_reduceable;
OCTREE next_alloc;
};
static void search_colors(OCTREE tree);
static void scan_large_tree(OCTREE tree);
static void reduce_large_octree();
static void norm_tree(OCTREE tree);
static void shorten_list();
#define RED 0
#define GREEN 1
#define BLUE 2
#define TRUE 1
#define FALSE 0
static LONG palette[FLI_MAX_COLORS];
static int octree_size;
static int reduce_level;
static int leaf_level;
static int reduce_start;
static OCTREE basetree;
static OCTREE reduce_list;
static int node_count[MAXDEPTH + 2];
static int reduce_count[MAXDEPTH + 1];
static int tree_count;
static OCTREE alloc_list=NULL;
static UBYTE b_field[]={128,64,32,16,8,4,2,1};
static double color_factor;
static int color_count;
/************************************************************************
* clr_quantize
************************************************************************/
int clr_quantize(PMS *input, UBYTE *p_output, LONG *color)
{
UBYTE b_red, b_green, b_blue, branch, btest;
UBYTE *pp;
OCTREE tree, next_tree, sub_tree;
int i,j,jmin,d1,d2,d3,dtest,dmin,unexpected;
double ratio;
pp = input->pixels;
unexpected=0;
for (i=0; i < input->len; i++)
{
b_red = *(pp++);
b_green = *(pp++);
b_blue = *(pp++);
tree=basetree;
next_tree=NULL;
while (tree->leaf == 0)
{
btest=b_field[tree->level];
branch=((b_red & btest) == 0) ? (UBYTE) 0 : (UBYTE) 4;
if ((b_green & btest) != 0) branch += (UBYTE) 2;
if ((b_blue & btest) != 0) branch += (UBYTE) 1;
next_tree=tree->sub[branch];
if (next_tree == NULL) break;
tree=next_tree;
}
if (next_tree == 0)
{
unexpected++;
while (tree->leaf == 0)
{
jmin=-1;
dmin=0;
for (j=0; j < 8; j++)
{
sub_tree=tree->sub[j];
if (sub_tree == NULL) continue;
d1=abs((int)sub_tree->rgb[RED] - (int)b_red);
d2=abs((int)sub_tree->rgb[GREEN] - (int)b_green);
d3=abs((int)sub_tree->rgb[BLUE] - (int)b_blue);
dtest=(d1 > d2) ? d1 : d2;
dtest=(d3 > dtest) ? d3 : dtest;
if ((jmin == -1) || (dtest < dmin))
{
dmin=dtest;
jmin=j;
}
}
if (jmin == -1)
{
fprintf(stdout,"Warning: %d\n",i);
break;
}
tree=tree->sub[jmin];
}
}
*(p_output++) = tree->color;
}
if (unexpected > 0)
{
ratio = 100.0 * unexpected/input->len;
fprintf(stdout," Quantize: %d non-fitting pixel(s) = %.4f %%\n",
unexpected, ratio);
}
for (i=0; i < FLI_MAX_COLORS; i++)
color[i]=palette[i];
return(color_count);
}
/************************************************************************
* prepare_quantize *
************************************************************************/
void prepare_quantize()
{
int i;
/* final reduction */
for (i=0; i <= MAXDEPTH; i++)
{
reduce_count[i]=0;
}
reduce_start = leaf_level - 1;
for (i = 1; i < leaf_level; i++)
{
if (node_count[i] >= max_colors)
{
reduce_start = i - 1;
break;
}
}
reduce_level = reduce_start + reduce_dynamics;
if (reduce_level >= leaf_level)
{
reduce_level = leaf_level - 1;
reduce_start = reduce_level - reduce_dynamics;
if (reduce_start < 0) reduce_start = 0;
}
else
{
leaf_level = reduce_level + 1;
}
/*
if (verbose_flag > 1)
{
fprintf(stdout," octree reduction in levels %d to %d\n",
reduce_start,
reduce_level);
}
*/
octree_size=0;
reduce_list=NULL;
scan_large_tree(basetree);
shorten_list();
while (octree_size > max_colors)
{
/* fprintf(stderr,"%d\n",octree_size); */
reduce_large_octree();
}
/***
if (verbose_flag > 1)
{
fprintf(stdout," Octree - reduce count:");
for (i=0; i <= MAXDEPTH; i++)
{
if ((i >= reduce_start) && (i <= reduce_level))
{
fprintf(stdout," %d", reduce_count[i]);
}
else
{
fprintf(stdout," -");
}
}
fprintf(stdout,"\n");
}
****/
/* now the colors */
for (i = 0; i < FLI_MAX_COLORS; i++) /* init palette */
palette[i] = 0;
color_count = 0;
color_factor = (double) ((1 << color_depth) - 1) / 0xFF;
for (i=0; i <= (MAXDEPTH+1); i++)
{node_count[i] = 0;}
search_colors(basetree);
if (verbose_flag > 0)
fprintf(stdout," Number of colors: %d\n",color_count);
if (verbose_flag > 1)
{
fprintf(stdout," Octree - leaf count (%d):", leaf_level);
for (i=0; i <= (MAXDEPTH + 1); i++)
{
fprintf(stdout," %d",node_count[i]);
}
fprintf(stdout,"\n");
}
for (i = color_count; i < FLI_MAX_COLORS; i++) /* no extra 0 0 0 */
palette[i] = palette[0];
}
/************************************************************************
* scan_rgb_image *
************************************************************************/
void scan_rgb_image(char *file_name)
{
PMS input;
fprintf(stdout,"Scanning '%s'\n",file_name);
input.pixels = (UBYTE *) NULL;
if (!read_image(&input, file_name))
{
fprintf(stderr,"Error processing '%s'\n",file_name);
exitialise(1);
exit(1);
}
add_to_large_octree(&input);
tree_count = 0;
norm_tree(basetree);
if (verbose_flag > 1)
{
fprintf(stdout," Octree - total size: %d\n",tree_count);
}
free_pms(&input);
}
/************************************************************************
* add_to_large_octree
************************************************************************/
void add_to_large_octree(PMS *image)
{
UBYTE b_red, b_green, b_blue, branch, btest;
UBYTE *pp;
OCTREE tree, *p_tree;
int i, depth, new_flag;
pp = image->pixels;
for (i=0; i < image->len; i++)
{
b_red = *(pp++);
b_green = *(pp++);
b_blue = *(pp++);
p_tree = &basetree;
new_flag = 0;
for (depth = 0; depth <= leaf_level; depth++)
{
if (*p_tree == NULL) /* init new node */
{
tree = (OCTREE) calloc(1, sizeof(struct node));
if (tree == NULL)
{
printf("Out of memory");
exit(1);
}
tree->next_alloc=alloc_list;
alloc_list=tree;
tree->level = depth;
(node_count[depth])++;
new_flag = 1;
*p_tree = tree;
}
else
tree = *p_tree;
tree->pixels_low++;
tree->red_sum_low += b_red;
tree->green_sum_low += b_green;
tree->blue_sum_low += b_blue;
if (depth < leaf_level)
{
btest=b_field[depth];
branch=((b_red & btest) == 0) ? (UBYTE) 0 : (UBYTE) 4;
if ((b_green & btest) != 0) branch += (UBYTE) 2;
if ((b_blue & btest) != 0) branch += (UBYTE) 1;
if (tree->sub[branch] == NULL)
tree->sub_count++;
p_tree=&(tree->sub[branch]);
}
}
if (new_flag)
{
for (depth = 0; depth < leaf_level; depth++)
{
if (node_count[depth] >= node_limit) /* reduce octree */
{
leaf_level=depth;
break;
}
}
}
}
for (depth = (leaf_level+1); depth <= (MAXDEPTH+1) ;depth++)
node_count[depth] = 0;
if (verbose_flag > 1)
{
fprintf(stdout," Octree - node count (%d):", leaf_level);
for (i=0; i <= (MAXDEPTH + 1); i++)
{
fprintf(stdout," %d",node_count[i]);
}
fprintf(stdout,"\n");
}
}
/************************************************************************
* clear_octree *
************************************************************************/
void clear_octree()
{
OCTREE next_node;
int i;
for (i=0; i <= MAXDEPTH+1; i++)
{
node_count[i]=0;
}
leaf_level = MAXDEPTH + 1;
basetree=NULL;
while (alloc_list != NULL)
{
next_node=alloc_list->next_alloc;
free(alloc_list);
alloc_list=next_node;
}
}
/************************************************************************
* output_palette
************************************************************************/
int output_palette()
{
LONG rgb_value;
int i, red, green, blue;
fprintf(output,"P3\n");
fprintf(output,"%d 1\n",color_count);
fprintf(output,"255\n");
fprintf(output,"# r g b index\n");
fprintf(output,"#---------------------\n");
for (i = 0; i < color_count; i++)
{
rgb_value = palette[i];
red=rgb_value % 256;
rgb_value=(rgb_value - red)/256;
green=rgb_value % 256;
rgb_value=(rgb_value - green)/256;
blue=rgb_value % 256;
fprintf(output," %3d %3d %3d # %d\n",red, green, blue, i);
}
return(1);
}
/************************************************************************
* search_colors
************************************************************************/
static void search_colors(OCTREE tree)
{
int j;
LONG rgb_value;
double dhelp0, dhelp1;
if (tree == NULL) return;
dhelp0=(double) tree->pixels_high * (double) BIGVAL
+(double) tree->pixels_low;
dhelp0=color_factor / dhelp0;
dhelp1=
(double) tree->red_sum_high * (double) BIGVAL
+(double) tree->red_sum_low;
tree->rgb[RED] = (char) (dhelp0 * dhelp1 + 0.5);
dhelp1=
(double) tree->green_sum_high * (double) BIGVAL
+(double) tree->green_sum_low;
tree->rgb[GREEN] = (char) (dhelp0 * dhelp1 + 0.5);
dhelp1=
(double) tree->blue_sum_high * (double) BIGVAL
+(double) tree->blue_sum_low;
tree->rgb[BLUE] = (char) (dhelp0 * dhelp1 + 0.5);
if (tree->leaf || tree->level == leaf_level)
{
rgb_value=(long int) tree->rgb[BLUE];
rgb_value=256L * rgb_value + (long int) tree->rgb[GREEN];
rgb_value=256L * rgb_value + (long int) tree->rgb[RED];
palette[color_count] = rgb_value;
tree->color = color_count;
tree->leaf = TRUE;
color_count++;
(node_count[tree->level])++;
}
else
{
for (j = 0; j < 8; j++)
search_colors(tree->sub[j]);
}
}
/************************************************************************
* scan_large_tree *
************************************************************************/
static void scan_large_tree(OCTREE tree)
{
int j;
if (tree == NULL) return;
if ((tree->level <= reduce_level) &&
(tree->level >= reduce_start))
{
if (tree->sub_count > 0)
{
tree->next_reduceable = reduce_list;
reduce_list = tree;
}
}
if (tree->level == leaf_level)
{
tree->leaf = TRUE;
octree_size++;
}
else
{
tree->leaf = FALSE;
for (j = 0; j < 8; j++)
scan_large_tree(tree->sub[j]);
}
}
/************************************************************************
* shorten_list()
************************************************************************/
static void shorten_list()
{
int i, flag, depth, n;
OCTREE tree, sub_tree, *p_tree;
p_tree = &reduce_list;
n = 0;
while ((tree = *p_tree) != NULL)
{
if (tree->sub_count == 1)
{
flag = 1;
for (i=0; i < 8; i++)
{
sub_tree=tree->sub[i];
if (sub_tree != NULL)
{ if (sub_tree->leaf == 0) {flag = 0;} }
}
if (flag == 1)
{
tree->leaf = 1;
depth = tree->level;
(reduce_count[depth])++;
*p_tree=tree->next_reduceable;
n++;
}
else
{
p_tree=&(tree->next_reduceable);
}
}
else
{
p_tree=&(tree->next_reduceable);
}
}
/***
if ((verbose_flag > 1) && (n > 0))
{
fprintf(stdout," Octree - drop count:");
for (i=0; i <= MAXDEPTH; i++)
{
if ((i >= reduce_start) && (i <= reduce_level))
{ fprintf(stdout," %d", reduce_count[i]);}
else
{ fprintf(stdout," -");}
}
fprintf(stdout,"\n");
}
****/
}
/************************************************************************
* reduce_large_octree
************************************************************************/
static void reduce_large_octree()
{
int i, flag, depth;
ULONG min_high, min_low;
OCTREE tree, sub_tree, *p_tree, *p_min;
if (reduce_list == NULL)
{
fprintf(stderr,"Internal error: ZERO reduce\n");
exit(1);
}
p_min = &reduce_list;
min_high = reduce_list->pixels_high;
min_low = reduce_list->pixels_low;
p_tree = &(reduce_list->next_reduceable);
while ((tree = *p_tree) != NULL)
{
flag = 1;
for (i=0; i < 8; i++)
{
sub_tree=tree->sub[i];
if (sub_tree != NULL)
{ if (sub_tree->leaf == 0) {flag = 0;} }
}
if (flag == 1)
{
if ((tree->pixels_high < min_high) ||
((tree->pixels_high == min_high) &&
(tree->pixels_low < min_low)))
{
p_min = p_tree;
min_high=tree->pixels_high;
min_low=tree->pixels_low;
}
}
p_tree=&(tree->next_reduceable);
}
tree = *p_min;
*p_min=tree->next_reduceable;
tree->leaf = 1;
octree_size = octree_size - tree->sub_count + 1;
depth = tree->level;
(reduce_count[depth])++;
}
/************************************************************************
* norm_tree *
************************************************************************/
static void norm_tree(OCTREE tree)
{
OCTREE subtree;
int i;
tree_count++;
while (tree->pixels_low >= BIGVAL)
{
tree->pixels_low -= BIGVAL;
tree->pixels_high++;
}
while (tree->red_sum_low >= BIGVAL)
{
tree->red_sum_low -= BIGVAL;
tree->red_sum_high++;
}
while (tree->green_sum_low >= BIGVAL)
{
tree->green_sum_low -= BIGVAL;
tree->green_sum_high++;
}
while (tree->blue_sum_low >= BIGVAL)
{
tree->blue_sum_low -= BIGVAL;
tree->blue_sum_high++;
}
if (tree->leaf == FALSE && tree->level < leaf_level)
{
for (i=0; i < 8; i++)
{
subtree=tree->sub[i];
if (subtree != NULL)
norm_tree(subtree);
}
}
}
/*** - FIN - ****************************************************************/
| C | CL | cb442707b1446258aacbc57a54f28cdc8f540400c267fdc75a0e4b76f19a3880 |
#ifndef _IAM_CONFIG_H_
#define _IAM_CONFIG_H_
#include <nn/vector.h>
struct nn_log;
struct iam_config {
struct nn_vector roles;
struct nn_vector policies;
};
void iam_config_init(struct iam_config* iamConfig);
void iam_config_deinit(struct iam_config* iamConfig);
bool load_iam_config(struct iam_config* iamConfig, const char* iamConfigFile, struct nn_log* logger);
#endif
| C | CL | 396ae0cfc801fa87d632a5fa640172cc7b3724b7f20a1782caadbc5ef54de192 |
#ifdef _MS_F_
#define dvmh_line_ dvmh_line
#define dvmh_init2_ dvmh_init2
#define dvmh_init_lib_ dvmh_init_lib
#define dvmh_exit_ dvmh_exit
#define dvmh_array_create_ dvmh_array_create
#define dvmh_template_create_ dvmh_template_create
#define dvmh_distribute_ dvmh_distribute
#define dvmh_redistribute2_ dvmh_redistribute2
#define dvmh_align_ dvmh_align
#define dvmh_realign2_ dvmh_realign2
#define dvmh_delete_object_ dvmh_delete_object
#define dvmh_forget_header_ dvmh_forget_header
#define dvmh_variable_fill_header_ dvmh_variable_fill_header
#define dvmh_variable_gen_header_ dvmh_variable_gen_header
#define dvmh_data_enter_ dvmh_data_enter
#define dvmh_data_exit_ dvmh_data_exit
#define dvmh_array_slice_ dvmh_array_slice
#define dvmh_array_copy_whole_ dvmh_array_copy_whole
#define dvmh_array_copy_ dvmh_array_copy
#define dvmh_fill_header2_ dvmh_fill_header2
#define dvmh_fill_header_ex2_ dvmh_fill_header_ex2
#define dvmh_get_actual_subvariable2_ dvmh_get_actual_subvariable2
#define dvmh_get_actual_variable2_ dvmh_get_actual_variable2
#define dvmh_get_actual_subarray2_ dvmh_get_actual_subarray2
#define dvmh_get_actual_array2_ dvmh_get_actual_array2
#define dvmh_get_actual_all2_ dvmh_get_actual_all2
#define dvmh_actual_subvariable2_ dvmh_actual_subvariable2
#define dvmh_actual_variable2_ dvmh_actual_variable2
#define dvmh_actual_subarray2_ dvmh_actual_subarray2
#define dvmh_actual_array2_ dvmh_actual_array2
#define dvmh_actual_all2_ dvmh_actual_all2
#define dvmh_shadow_renew2_ dvmh_shadow_renew2
#define dvmh_indirect_shadow_renew_ dvmh_indirect_shadow_renew
#define dvmh_indirect_localize_ dvmh_indirect_localize
#define dvmh_indirect_unlocalize_ dvmh_indirect_unlocalize
#define dvmh_remote_access2_ dvmh_remote_access2
#define dvmh_has_element_ dvmh_has_element
#define dvmh_calc_linear_ dvmh_calc_linear
#define dvmh_region_create_ dvmh_region_create
#define dvmh_region_register_subarray_ dvmh_region_register_subarray
#define dvmh_region_register_array_ dvmh_region_register_array
#define dvmh_region_register_scalar_ dvmh_region_register_scalar
#define dvmh_region_execute_on_targets_ dvmh_region_execute_on_targets
#define dvmh_region_end_ dvmh_region_end
#define dvmh_loop_create_ dvmh_loop_create
#define dvmh_loop_map_ dvmh_loop_map
#define dvmh_loop_set_cuda_block_ dvmh_loop_set_cuda_block
#define dvmh_loop_set_stage_ dvmh_loop_set_stage
#define dvmh_loop_reduction_ dvmh_loop_reduction
#define dvmh_loop_across_ dvmh_loop_across
#define dvmh_loop_shadow_compute_ dvmh_loop_shadow_compute
#define dvmh_loop_consistent_ dvmh_loop_consistent
#define dvmh_loop_remote_access_ dvmh_loop_remote_access
#define dvmh_loop_register_handler_ dvmh_loop_register_handler
#define dvmh_loop_perform_ dvmh_loop_perform
#define dvmh_loop_get_dependency_mask_ dvmh_loop_get_dependency_mask
#define dvmh_loop_get_device_num_ dvmh_loop_get_device_num
#define dvmh_loop_autotransform_ dvmh_loop_autotransform
#define dvmh_loop_fill_bounds_ dvmh_loop_fill_bounds
#define dvmh_loop_get_slot_count_ dvmh_loop_get_slot_count
#define dvmh_loop_fill_local_part_ dvmh_loop_fill_local_part
#define dvmh_loop_guess_index_type_ dvmh_loop_guess_index_type
#define dvmh_loop_get_remote_buf_ dvmh_loop_get_remote_buf
#define dvmh_loop_red_init_ dvmh_loop_red_init
#define dvmh_loop_has_element_ dvmh_loop_has_element
#define dvmh_loop_red_post_ dvmh_loop_red_post
#define dvmh_scope_start_ dvmh_scope_start
#define dvmh_scope_insert_ dvmh_scope_insert
#define dvmh_scope_end_ dvmh_scope_end
#define dvmh_interval_start_ dvmh_interval_start
#define dvmh_interval_end_ dvmh_interval_end
#define dvmh_get_addr_ dvmh_get_addr
#define dvmh_string_ dvmh_string
#define dvmh_string_var_ dvmh_string_var
#define dvmh_ftn_open_ dvmh_ftn_open
#define dvmh_ftn_close_ dvmh_ftn_close
#define dvmh_ftn_connected_ dvmh_ftn_connected
#define dvmh_ftn_read_unf_ dvmh_ftn_read_unf
#define dvmh_ftn_write_unf_ dvmh_ftn_write_unf
#define dvmh_ftn_endfile_ dvmh_ftn_endfile
#define dvmh_ftn_rewind_ dvmh_ftn_rewind
#define dvmh_ftn_flush_ dvmh_ftn_flush
#endif
| C | CL | 1da61fc7894aa8f4d6758572db873b63c9a4e813325511fc11f808f2afc562d8 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct phy_device {int dummy; } ;
struct net_device {struct phy_device* phydev; } ;
struct ftgmac100 {scalar_t__ aneg_pause; int /*<<< orphan*/ rx_pause; int /*<<< orphan*/ tx_pause; } ;
struct ethtool_pauseparam {int /*<<< orphan*/ tx_pause; int /*<<< orphan*/ rx_pause; scalar_t__ autoneg; } ;
/* Variables and functions */
int /*<<< orphan*/ ftgmac100_config_pause (struct ftgmac100*) ;
struct ftgmac100* netdev_priv (struct net_device*) ;
scalar_t__ netif_running (struct net_device*) ;
int /*<<< orphan*/ phy_set_asym_pause (struct phy_device*,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
__attribute__((used)) static int ftgmac100_set_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pause)
{
struct ftgmac100 *priv = netdev_priv(netdev);
struct phy_device *phydev = netdev->phydev;
priv->aneg_pause = pause->autoneg;
priv->tx_pause = pause->tx_pause;
priv->rx_pause = pause->rx_pause;
if (phydev)
phy_set_asym_pause(phydev, pause->rx_pause, pause->tx_pause);
if (netif_running(netdev)) {
if (!(phydev && priv->aneg_pause))
ftgmac100_config_pause(priv);
}
return 0;
} | C | CL | 0b0b5168ad34e1eac6ce4b6a41e794d9ef487a53a575b039377e987a26e4ace8 |
/**
* \file handlerrunners.c
* \author Christian Kruse, <[email protected]>
* \brief server communication functions
*
* This file contains functions to communicate with the forum server
*/
/* {{{ Initial comments */
/*
* $LastChangedDate$
* $LastChangedRevision$
* $LastChangedBy$
*
*/
/* }}} */
/* {{{ Includes */
#include "cfconfig.h"
#include "defines.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#ifdef CF_SHARED_MEM
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#endif
#include <inttypes.h>
#include <sys/types.h>
#include "hashlib.h"
#include "utils.h"
#include "cfgcomp.h"
#include "template.h"
#include "readline.h"
#include "charconvert.h"
#include "clientlib.h"
/* }}} */
/* {{{ cf_get_threadlist */
#ifndef CF_SHARED_MEM
int cf_get_threadlist(cf_array_t *ary,int sock,rline_t *tsd)
#else
int cf_get_threadlist(cf_array_t *ary,int shmids[3],void *ptr)
#endif
{
cf_cl_thread_t thread;
cf_array_init(ary,sizeof(thread),(void (*)(void *))cf_cleanup_thread);
#ifndef CF_SHARED_MEM
while(cf_get_next_thread_through_sock(sock,tsd,&thread) == 0)
#else
while((ptr = cf_get_next_thread_through_shm(ptr,shmids,&thread)) != NULL)
#endif
{
cf_array_push(ary,&thread);
memset(&thread,0,sizeof(thread));
}
return 0;
}
/* }}} */
/* {{{ cf_get_next_thread_through_sock */
int cf_get_next_thread_through_sock(int sock,rline_t *tsd,cf_cl_thread_t *thr) {
u_char *line,*chtmp;
int shallRun = 1;
cf_message_t *x;
int ok = 0;
cf_post_flag_t flag;
memset(thr,0,sizeof(*thr));
/* now lets read the threadlist */
while(shallRun) {
line = readline(sock,tsd);
if(line) {
line[tsd->rl_len-1] = '\0';
if(*line == '\0') shallRun = 0;
else if(cf_strncmp(line,"THREAD t",8) == 0) {
chtmp = strstr(line,"m");
thr->messages = cf_alloc(NULL,1,sizeof(*thr->messages),CF_ALLOC_CALLOC);
thr->last = thr->messages;
thr->newest = thr->messages;
thr->last->mid = cf_str_to_uint64(chtmp+1);
thr->messages->may_show = 1;
thr->msg_len = 1;
thr->tid = cf_str_to_uint64(line+8);
cf_tpl_var_init(&thr->messages->hashvar,TPL_VARIABLE_HASH);
}
else if(cf_strncmp(line,"MSG m",5) == 0) {
x = thr->last;
if(thr->last) {
thr->last->next = cf_alloc(NULL,1,sizeof(*thr->last->next),CF_ALLOC_CALLOC);
thr->last->next->prev = thr->last;
thr->last = thr->last->next;
}
else {
thr->messages = cf_alloc(NULL,1,sizeof(thr->messages),CF_ALLOC_CALLOC);
thr->last = thr->messages;
}
thr->last->mid = cf_str_to_uint64(line+5);
thr->last->may_show = 1;
thr->msg_len++;
cf_tpl_var_init(&thr->last->hashvar,TPL_VARIABLE_HASH);
}
else if(cf_strncmp(line,"Flag:",5) == 0) {
chtmp = strstr(line+5,"=");
flag.name = strndup(line+5,chtmp-line-5);
flag.val = strndup(chtmp+1,strlen(chtmp+1));
cf_list_append(&thr->last->flags,&flag,sizeof(flag));
}
else if(cf_strncmp(line,"Date:",5) == 0) {
thr->last->date = strtoul(line+5,NULL,10);
if(thr->last->date > thr->newest->date) thr->newest = thr->last;
}
else if(cf_strncmp(line,"Author:",7) == 0) cf_str_char_set(&thr->last->author,line+7,tsd->rl_len-8);
else if(cf_strncmp(line,"Subject:",8) == 0) cf_str_char_set(&thr->last->subject,line+8,tsd->rl_len-9);
else if(cf_strncmp(line,"Category:",9) == 0) cf_str_char_set(&thr->last->category,line+9,tsd->rl_len-10);
else if(cf_strncmp(line,"Level:",6) == 0) thr->last->level = atoi(line+6);
else if(cf_strncmp(line,"Content:",8) == 0) cf_str_char_set(&thr->last->content,line+8,tsd->rl_len-9);
else if(cf_strncmp(line,"Homepage:",9) == 0) cf_str_char_set(&thr->last->hp,line+9,tsd->rl_len-10);
else if(cf_strncmp(line,"Image:",6) == 0) cf_str_char_set(&thr->last->img,line+6,tsd->rl_len-7);
else if(cf_strncmp(line,"EMail:",6) == 0) cf_str_char_set(&thr->last->email,line+6,tsd->rl_len-7);
else if(cf_strncmp(line,"Votes-Good:",11) == 0) thr->last->votes_good = strtoul(line+11,NULL,10);
else if(cf_strncmp(line,"Votes-Bad:",10) == 0) thr->last->votes_bad = strtoul(line+10,NULL,10);
else if(cf_strncmp(line,"Remote-Addr:",12) == 0) cf_str_char_set(&thr->last->remote_addr,line+12,tsd->rl_len-13);
else if(cf_strncmp(line,"Visible:",8) == 0) {
thr->last->invisible = line[8] == '0';
if(thr->last->invisible) thr->msg_len--;
}
else if(cf_strncmp(line,"END",3) == 0) {
shallRun = 0;
ok = 1;
}
free(line);
}
else {
shallRun = 0; /* connection broke */
strcpy(ErrorString,"E_COMMUNICATE");
}
}
if(ok) {
/* {{{ build hierarchical structure */
thr->ht = cf_alloc(NULL,1,sizeof(*thr->ht),CF_ALLOC_CALLOC);
thr->ht->msg = thr->messages;
if(thr->messages->next) cf_msg_build_hierarchical_structure(thr->ht,thr->messages->next);
/* }}} */
return 0;
}
return -1;
}
/* }}} */
/* {{{ cf_get_next_thread_through_shm */
#ifdef CF_SHARED_MEM
void *cf_get_next_thread_through_shm(int shmids[3],void *shm_ptr,cf_cl_thread_t *thr) {
register void *ptr = shm_ptr;
u_int32_t post,i,val,val1;
struct shmid_ds shm_buf;
void *ptr1 = cf_get_shm_ptr(shmids);
u_int32_t msglen;
cf_post_flag_t flag;
memset(thr,0,sizeof(*thr));
if(shmctl(shm_id,IPC_STAT,&shm_buf) != 0) {
strcpy(ErrorString,"E_CONFIG_ERR");
return NULL;
}
/*
*
* CAUTION! Deep magic begins here! Do not edit if you don't know
* what you are doing!
*
*/
/* Uh, oh, we are at the end of the segment */
if(ptr >= ptr1 + shm_buf.shm_segsz) return NULL;
/* thread id */
thr->tid = *((u_int64_t *)ptr);
ptr += sizeof(u_int64_t);
/* message id */
thr->msg_len = msglen = *((u_int32_t *)ptr);
ptr += sizeof(u_int32_t);
for(post = 0;post < msglen;++post) {
if(thr->last == NULL) thr->messages = thr->last = cf_alloc(NULL,1,sizeof(*thr->last),CF_ALLOC_CALLOC);
else {
thr->last->next = cf_alloc(NULL,1,sizeof(*thr->last->next),CF_ALLOC_CALLOC);
thr->last->next->prev = thr->last;
thr->last = thr->last->next;
}
if(!thr->newest) thr->newest = thr->last;
cf_tpl_var_init(&thr->last->hashvar,TPL_VARIABLE_HASH);
/* {{{ message id */
thr->last->mid = *((u_int64_t *)ptr);
ptr += sizeof(u_int64_t);
/* }}} */
/* {{{ flags */
val = *((u_int32_t *)ptr);
ptr += sizeof(u_int32_t);
for(i=0;i<val;++i) {
val1 = *((u_int32_t *)ptr);
ptr += sizeof(u_int32_t);
flag.name = strndup(ptr,val1);
ptr += val1;
val1 = *((u_int32_t *)ptr);
ptr += sizeof(u_int32_t);
flag.val = strndup(ptr,val1);
ptr += val1;
cf_list_append(&thr->last->flags,&flag,sizeof(flag));
}
/* }}} */
/* {{{ subject */
/* length of subject */
val = *((u_int32_t *)ptr) - 1;
ptr += sizeof(u_int32_t);
/* subject */
cf_str_char_set(&thr->last->subject,ptr,val);
ptr += val + 1;
/* }}} */
/* {{{ category */
/* length of category */
val = *((u_int32_t *)ptr) - 1;
ptr += sizeof(u_int32_t);
/* category */
if(val) {
cf_str_char_set(&thr->last->category,ptr,val);
ptr += val + 1;
}
/* }}} */
/* {{{ the remote address */
val = *((u_int32_t *)ptr) - 1;
ptr += sizeof(u_int32_t);
cf_str_char_set(&thr->last->remote_addr,ptr,val);
ptr += val + 1;
/* }}} */
/* {{{ content */
/* content length */
val = *((u_int32_t *)ptr) - 1;
ptr += sizeof(u_int32_t);
/* content */
cf_str_char_set(&thr->last->content,ptr,val);
ptr += val + 1;
/* }}} */
/* {{{ date */
thr->last->date = *((time_t *)ptr);
ptr += sizeof(time_t);
if(thr->last->date > thr->newest->date) thr->newest = thr->last;
/* }}} */
/* {{{ level */
thr->last->level = *((u_int16_t *)ptr);
ptr += sizeof(u_int16_t);
/* }}} */
/* {{{ invisible */
thr->last->invisible = *((u_int16_t *)ptr);
thr->last->may_show = 1;
ptr += sizeof(u_int16_t);
/* }}} */
if(thr->last->invisible) thr->msg_len--;
/* {{{ votings */
thr->last->votes_good = *((u_int32_t *)ptr);
ptr += sizeof(u_int32_t);
thr->last->votes_bad = *((u_int32_t *)ptr);
ptr += sizeof(u_int32_t);
/* }}} */
/* {{{ author */
/* author length */
val = *((u_int32_t *)ptr) - 1;
ptr += sizeof(u_int32_t);
/* author */
cf_str_char_set(&thr->last->author,ptr,val);
ptr += val + 1;
/* }}} */
/* {{{ email */
/* email length */
val = *((u_int32_t *)ptr);
ptr += sizeof(u_int32_t);
/* email */
if(val) {
cf_str_char_set(&thr->last->email,ptr,val-1);
ptr += val;
}
/* }}} */
/* {{{ homepage */
/* homepage length */
val = *((u_int32_t *)ptr);
ptr += sizeof(u_int32_t);
/* homepage */
if(val) {
cf_str_char_set(&thr->last->hp,ptr,val-1);
ptr += val;
}
/* }}} */
/* {{{ image */
/* image length */
val = *((u_int32_t *)ptr);
ptr += sizeof(u_int32_t);
/* image */
if(val) {
cf_str_char_set(&thr->last->img,ptr,val-1);
ptr += val;
}
/* }}} */
}
/* {{{ build hierarchical structure */
thr->ht = cf_alloc(NULL,1,sizeof(*thr->ht),CF_ALLOC_CALLOC);
thr->ht->msg = thr->messages;
if(thr->messages->next) cf_msg_build_hierarchical_structure(thr->ht,thr->messages->next);
/* }}} */
return ptr;
}
#endif
/* }}} */
/* {{{ cf_get_message_through_sock */
int cf_get_message_through_sock(int sock,rline_t *tsd,cf_cl_thread_t *thr,u_int64_t tid,u_int64_t mid,int del) {
size_t len;
u_char buff[128],*line;
cf_message_t *msg;
u_char *forum_name = cf_hash_get(GlobalValues,"FORUM_NAME",10);
memset(thr,0,sizeof(*thr));
len = snprintf(buff,128,"SELECT %s\n",forum_name);
writen(sock,buff,len);
line = readline(sock,tsd);
if(line && cf_strncmp(line,"200 Ok",6) == 0) {
free(line);
len = snprintf(buff,128,"GET POSTING t%" PRIu64 " m%" PRIu64 " invisible=%d\n",tid,mid,del);
writen(sock,buff,len);
line = readline(sock,tsd);
if(line && cf_strncmp(line,"200 Ok",6) == 0) {
free(line);
thr->tid = tid;
thr->messages = NULL;
thr->ht = NULL;
thr->last = NULL;
if(cf_get_next_thread_through_sock(sock,tsd,thr) < 0 && *ErrorString) {
strcpy(ErrorString,"E_COMMUNICATION");
return -1;
}
else {
/* set thread message pointer to the right message */
if(mid == 0) thr->threadmsg = thr->messages;
else {
for(msg = thr->messages;msg;msg=msg->next) {
if(msg->mid == mid) {
thr->threadmsg = msg;
break;
}
}
}
}
}
else {
/* bye, bye */
if(line) {
snprintf(ErrorString,50,"E_FO_%d",atoi(line));
free(line);
}
else strcpy(ErrorString,"E_COMMUNICATION");
return -1;
}
}
else {
if(line) {
snprintf(ErrorString,50,"E_FO_%d",atoi(line));
free(line);
}
else strcpy(ErrorString,"E_COMMUNICATION");
return -1;
}
return 0;
}
/* }}} */
/* {{{ cf_get_message_through_shm */
#ifdef CF_SHARED_MEM
int cf_get_message_through_shm(int shmids[3],void *shm_ptr,cf_cl_thread_t *thr,u_int64_t tid,u_int64_t mid,int del) {
struct shmid_ds shm_buf;
register void *ptr1;
u_int64_t val = 0;
size_t posts,post,x,flagnum;
cf_message_t *msg;
if(shmctl(shm_id,IPC_STAT,&shm_buf) != 0) {
strcpy(ErrorString,"E_CONFIG_ERR");
return -1;
}
/*
*
* CAUTION! Deep magic begins here! Do not edit if you don't know
* what you are doing
*
*/
for(ptr1=shm_ptr+sizeof(time_t);ptr1 < shm_ptr+shm_buf.shm_segsz;) {
/* first: tid */
val = *((u_int64_t *)ptr1);
if(val == tid) break;
ptr1 += sizeof(u_int64_t);
/* after that: number of postings */
posts = *((int32_t *)ptr1);
ptr1 += sizeof(int32_t);
for(post = 0;post < posts;post++) {
/* then: message id */
ptr1 += sizeof(u_int64_t);
/* number of flags */
flagnum = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t);
for(x=0;x<flagnum;++x) {
/* size of name */
val = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t) + val;
val = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t) + val;
}
/* then: length of the subject + subject */
val = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t) + val;
/* length of the category + category */
val = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t);
if(val) ptr1 += val;
/* remote address */
val = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t) + val;
/* length of the content + content */
val = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t) + val;
/* date, level, invisible, votes good, votes bad */
ptr1 += sizeof(time_t) + sizeof(u_int16_t) + sizeof(u_int16_t) + sizeof(u_int32_t) + sizeof(u_int32_t);
/* user name length + user name */
val = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t) + val;
/* email length + email */
val = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t);
if(val) ptr1 += val;
/* homepage length + homepage */
val = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t);
if(val) ptr1 += val;
/* image length + image */
val = *((u_int32_t *)ptr1);
ptr1 += sizeof(u_int32_t);
if(val) ptr1 += val;
}
}
/*
*
* Phew, deep magic ended
*
*/
if(ptr1 >= shm_ptr + shm_buf.shm_segsz) {
strcpy(ErrorString,"E_FO_404");
return -1;
}
if((ptr1 = cf_get_next_thread_through_shm(shmids,ptr1,thr)) == NULL) return -1;
if(mid == 0) thr->threadmsg = thr->messages;
else {
for(msg=thr->messages;msg;msg=msg->next) {
if(msg->mid == mid) {
thr->threadmsg = msg;
break;
}
}
}
if(!thr->threadmsg) {
strcpy(ErrorString,"E_FO_404");
return -1;
}
if((thr->messages->invisible == 1 || thr->threadmsg->invisible == 1) && del == CF_KILL_DELETED) {
strcpy(ErrorString,"E_FO_404");
return -1;
}
return 0;
}
#endif
/* }}} */
/* eof */
| C | CL | 41bc012372452d89db825e82c6a3f5bef85535599f6c3f4757d8323bbd5aafd1 |
#ifndef ROTARY_ENCODER_C_H
#define ROTARY_ENCODER_C_H
#include "../core/core.h"
typedef struct
{
/* Configuration Variables */
GPIO_TypeDef* SignalAGPIOX;
GPIO_TypeDef* SignalBGPIOX;
GPIO_TypeDef* ButtonGPIOX;
uint SignalBPin;
uint SignalAPin;
uint ButtonPin;
void (*OnRotaryEncoderAdjust)(void);
void (*OnRotaryEncoderPressed)(void);
uint Mapping;
/* Private Variables */
EXTIInstance _SignalEXTI;
EXTIInstance _ButtonEXTI;
ulong _DebounceTime;
/* State Variables */
uint Count;
uint Delta;
uint Absolute;
uint LastA;
int Value;
bool Incremented;
}RotaryEncoder;
void rotary_encoder_init(RotaryEncoder* instance);
#endif
| C | CL | f859d1c0400dd6469ab1f4aff77f8f7f60b5c2d71421af763428b8349520ea6d |
#include <jni.h>
#include <sys/types.h>
#include "iostream.h"
#include "ansi.h"
#include "LiaisonBody.h"
#include "LiaisonBody_e.h"
EXTERN int vt_initialize(void); /*definie dans vt_body.c */
EXTERN int vt_iterate(void); /*definie dans vt_body.c */
JNIEnv *env_appel_vt;
jobject obj_appel_vt;
jclass cls;
jmethodID mid_wstop; /* identifie la methode wstop */
jmethodID mid_dca1; /* identifie la methode dessine_chat */
jmethodID mid_dca2; /* identifie la methode dessine_souris */
jmethodID mid_dca3; /* identifie la methode dessine_porte_chat */
jmethodID mid_dca4; /* identifie la methode dessine_porte_souris */
jmethodID mid_ac; /* identifie la methode Draw_Conflict */
jmethodID mid_rp; /* identifie la methode reset_panel */
jmethodID mid_resolv; /* identifie la methode resolveur */
jmethodID mid_ev; /* identifie la methode ecritVitesse */
int nb_etat, nb_cond, nb_ent_cont, nb_ent_incont;
JNIEXPORT void JNICALL Java_LiaisonBody_connexionBody
(JNIEnv *env, jobject obj){
cls=env->GetObjectClass(obj);
env_appel_vt=env;
obj_appel_vt=obj;
mid_dca2=env->GetMethodID(cls,"Draw","(ZZZ)V");
if (mid_dca2 == 0) {cout << "GetMethodID a echoue avec Draw \n";};
mid_wstop=env->GetMethodID(cls,"wstop","()V");
if (mid_wstop == 0) {cout << "GetStaticMethodID a echoue avec wstop \n";};
mid_rp=env->GetMethodID(cls,"reset_panel","(Z)V");
if (mid_rp == 0) {cout << "GetMethodID a echoue avec reset_panel \n";};
mid_resolv=env->GetMethodID(cls,"resolver","([I[I[I[I[Z)V");
if (mid_resolv == 0) {cout << "GetMethodID a echoue avec resolver \n";};
}
JNIEXPORT void JNICALL Java_LiaisonBody_n_1set_1variable
(JNIEnv *env, jobject obj, jint nbEtat, jint nbCond, jint nbEntCont , jint nbEntIncont ){
nb_etat = (int) nbEtat;
nb_cond = (int) nbCond;
nb_ent_cont = (int) nbEntCont;
nb_ent_incont = (int) nbEntIncont;
}
JNIEXPORT jboolean JNICALL Java_LiaisonBody_n_1vt_1initialise
(JNIEnv *env, jobject obj){
return (jboolean) vt_initialize();
}
JNIEXPORT jboolean JNICALL Java_LiaisonBody_n_1vt_1iterate
(JNIEnv *env, jobject obj){
return (jboolean) vt_iterate();
}
extern void WSTOP(long int *b){
env_appel_vt->CallVoidMethod(obj_appel_vt,mid_wstop);
}
extern void Draw_Conflict(int Conflict){
env_appel_vt->CallVoidMethod(obj_appel_vt,mid_ac,Conflict);
}
/* Lecture de l'horloge */
extern boolean r_vt_HE(int *h1){
*h1 = TRUE;
return TRUE;
}
/* Lecture de l'horloge
extern void rhe(int *h1,int *h2){
*h1 = TRUE;
*h2 = TRUE;
} */
extern void RESET_PANEL(boolean cauto)
{
jboolean bool_auto = (cauto==TRUE);
env_appel_vt->CallVoidMethod(obj_appel_vt,mid_rp,bool_auto);
}
extern void resolver(int cod_cond[], int cod_x[], int cod_u[],
int cod_y[], boolean *fin_resolver)
{
int i;
/* preparation des parametres */
jint *tampon_cod_cond;
tampon_cod_cond = new jint[nb_cond];
for (i=0; i<nb_cond; i++) tampon_cod_cond[i]=(jint)cod_cond[i];
jintArray Cod_cond = env_appel_vt->NewIntArray(nb_cond);
env_appel_vt->SetIntArrayRegion(Cod_cond,0,nb_cond,&*tampon_cod_cond);
jint *tampon_cod_x;
tampon_cod_x = new jint[nb_etat];
for ( i=0; i<nb_etat; i++) tampon_cod_x[i]=(jint)cod_x[i];
jintArray Cod_x = env_appel_vt->NewIntArray(nb_etat);
env_appel_vt->SetIntArrayRegion(Cod_x,0,nb_etat,&*tampon_cod_x);
jint *tampon_cod_u;
tampon_cod_u = new jint[nb_ent_cont];
for ( i=0; i<nb_ent_cont; i++) tampon_cod_u[i]=(jint)cod_u[i];
jintArray Cod_u = env_appel_vt->NewIntArray(nb_ent_cont);
env_appel_vt->SetIntArrayRegion(Cod_u,0,nb_ent_cont,&*tampon_cod_u);
jint *tampon_cod_y;
tampon_cod_y = new jint[nb_ent_incont];
for ( i=0; i<nb_ent_incont; i++) tampon_cod_y[i]=(jint)cod_y[i];
jintArray Cod_y = env_appel_vt->NewIntArray(nb_ent_incont);
env_appel_vt->SetIntArrayRegion(Cod_y,0,nb_ent_incont,&*tampon_cod_y);
jboolean tampon_fin_r[1];
tampon_fin_r[0]=(jboolean)*fin_resolver;
jbooleanArray Fin_resolver = env_appel_vt->NewBooleanArray(1);
env_appel_vt->SetBooleanArrayRegion(Fin_resolver,0,1,tampon_fin_r);
/* appel de la methode resolver ecrite en java */
env_appel_vt->CallVoidMethod(obj_appel_vt,mid_resolv,Cod_cond,Cod_x,Cod_u,Cod_y,Fin_resolver);
/* recuperation des valeurs */
jint *t_cod_cond=env_appel_vt->GetIntArrayElements(Cod_cond,0);
for ( i=0; i<nb_cond; i++) cod_cond[i]=(int)t_cod_cond[i];
jint *t_cod_x=env_appel_vt->GetIntArrayElements(Cod_x,0);
for ( i=0; i<nb_etat; i++) cod_x[i]=(int)t_cod_x[i];
jint *t_cod_u=env_appel_vt->GetIntArrayElements(Cod_u,0);
for ( i=0; i<nb_ent_cont; i++) cod_u[i]=(int)t_cod_u[i];
jint *t_cod_y=env_appel_vt->GetIntArrayElements(Cod_y,0);
for ( i=0; i<nb_ent_incont; i++) cod_y[i]=(int)t_cod_y[i];
jboolean *fin_r=env_appel_vt->GetBooleanArrayElements(Fin_resolver,0);
*fin_resolver = (boolean)*fin_r;
}
/*------------------ write an integer number */
/* Dans la version original (C++/Motif), */
/* cette procedure etait dans common.c */
/* elle permetait d'afficher un nombre */
/* dans un widget passe en parametre. */
/* Pour simplifier, et etant donne que */
/* vt_body n'utilise cette fonction que */
/* pour ecrire la vitesse dans le pacemaker, */
/* on ne va pas utiliser le pointeur sur le widget. */
extern void WIWRITE(int *w_pt, int v)
{
env_appel_vt->CallVoidMethod(obj_appel_vt,mid_ev,v);
}
extern void Draw(boolean Flow_Pump, boolean Flow_Valve2, boolean Valve2)
{
env_appel_vt->CallVoidMethod(obj_appel_vt,mid_dca2,Flow_Pump,Flow_Valve2,Valve2);
}
| C | CL | 726283d89121ef11c3ac30915450f33ed403c2012a55d14e547b5c227e697a13 |
/*
* Routines dealing with the "position" table.
* This is a table which tells the position (in the input file) of the
* first char on each currently displayed line.
*
* {{ The position table is scrolled by moving all the entries.
* Would be better to have a circular table
* and just change a couple of pointers. }}
*/
#include "less.h"
#include "position.h"
#define NPOS 100 /* {{ sc_height must be less than NPOS }} */
static POSITION table[NPOS]; /* The position table */
extern int sc_width, sc_height;
/*
* Return the starting file position of a line displayed on the screen.
* The line may be specified as a line number relative to the top
* of the screen, but is usually one of these special cases:
* the top (first) line on the screen
* the second line on the screen
* the bottom line on the screen
* the line after the bottom line on the screen
*/
public POSITION
position(where)
int where;
{
switch (where)
{
case BOTTOM:
where = sc_height - 2;
break;
case BOTTOM_PLUS_ONE:
where = sc_height - 1;
break;
}
return (table[where]);
}
/*
* Add a new file position to the bottom of the position table.
*/
public void
add_forw_pos(pos)
POSITION pos;
{
register int i;
/*
* Scroll the position table up.
*/
for (i = 1; i < sc_height; i++)
table[i-1] = table[i];
table[sc_height - 1] = pos;
}
/*
* Add a new file position to the top of the position table.
*/
public void
add_back_pos(pos)
POSITION pos;
{
register int i;
/*
* Scroll the position table down.
*/
for (i = sc_height - 1; i > 0; i--)
table[i] = table[i-1];
table[0] = pos;
}
/*
* Initialize the position table, done whenever we clear the screen.
*/
public void
pos_clear()
{
register int i;
for (i = 0; i < sc_height; i++)
table[i] = NULL_POSITION;
}
/*
* See if the byte at a specified position is currently on the screen.
* Check the position table to see if the position falls within its range.
* Return the position table entry if found, -1 if not.
*/
public int
onscreen(pos)
POSITION pos;
{
register int i;
if (pos < table[0])
return (-1);
for (i = 1; i < sc_height; i++)
if (pos < table[i])
return (i-1);
return (-1);
}
| C | CL | e0faba7c819b5b322c0f0f9425e8dc4e3b143e111339f8e03d5605f5e519fb34 |
#ifndef __MAIN_H
#define __MAIN_H
#include "ucos_ii.h"
#include "qxwz_rtcm.h"
#include "usart.h"
#include "bluetooth.h"
#include "wt5883.h"
#include "key_pow.h"
#include "ad.h"
#include "spi.h"
#include "fm25v01.h"
#include "sim7600.h"
#include "ef_qx.h"
#include "led.h"
#include "delay.h"
#include "includes.h"
#include "qxwz_rtcm.h"
#include "socket.h"
#include "prefs.h"
//#define BOOT_LOADER //定义了升级程序
#define BOOT_APP_BASE 0x0004000 //定义boot后的基地址
#define TIMER_FEQ 1
/////////////////////////UCOSII任务设置///////////////////////////////////
//主任务
#define START_TASK_PRIO 13 //设置任务优先级
#define START_STK_SIZE 64 //设置任务堆栈大小
void start_task(void *pdata);//任务函数
//LED0任务
#define Tick_TASK_PRIO 7//设置任务优先级
#define Tick_STK_SIZE 512//设置任务堆栈大小
void Tick_task(void *pdata);//任务函数
//SENDGGA任务
#define SENDGGA_TASK_PRIO 8 //设置任务优先级
#define SENDGGA_STK_SIZE 512//设置任务堆栈大小
void sendgga_task(void *pdata);//任务函数
//RTCM任务 该任务优先级应该低
#define RTCM_TASK_PRIO 12//设置任务优先级
#define RTCM_STK_SIZE 2048//设置任务堆栈大小
void rtcm_task(void *pdata);//任务函数
//串口1数据处理任务
#define USART1_TASK_PRIO 5//设置任务优先级
#define USART1_STK_SIZE 2048//设置任务堆栈大小
void USART1_task(void *pdata);//任务函数
//串口2数据处理任务
#define USART2_TASK_PRIO 4//设置任务优先级
#define USART2_STK_SIZE 2048//设置任务堆栈大小
void USART2_task(void *pdata);//任务函数
//串口3数据处理任务
#define USART3_TASK_PRIO 6//设置任务优先级
#define USART3_STK_SIZE 512//设置任务堆栈大小
void USART3_task(void *pdata);//任务函数
//按键任务
#define KEY_TASK_PRIO 3//设置任务优先级
#define KEY_STK_SIZE 64//设置任务堆栈大小
void KEY_task(void *pdata);//任务函数
//电量检测
#define AD_TASK_PRIO 11//设置任务优先级
#define AD_STK_SIZE 64//设置任务堆栈大小
void AD_task(void *pdata);//任务函数
//////////////////////////////////////////////////////////////////////////
/*************信号量****************************************/
extern OS_EVENT *USART1_Semp;
extern OS_EVENT *USART2_Semp;
extern OS_EVENT *USART3_Semp;
/*****************************************************/
typedef union
{
unsigned int task_flag_all;
struct
{
unsigned Send_Rtcm_Flag; /*if true start send rtcm date*/
unsigned Get_Cunt_Ok; /*if true get qianxun cunt ok*/
unsigned Pow_On; /*if true power on*/
unsigned Pow_Off; /*if true power off*/
unsigned Debug_Date; /*if true debug to bluetooth*/
unsigned Move_Station; /*if true that is move_Staion*/
unsigned Send_Gpgga; /*if true net can send gpgga*/
}Flag_Bit;
}task_flag;
extern task_flag Task_Flag;
void restart_connect(void);
void async_notify(void);
void timer_tick(uint16_t tick_feq);
void get_qxwz_sdk_status(qxwz_rtcm_status_code status);
#endif
| C | CL | b8e84d3558062859d88c186a412eeed18ef6bb33ea7d22cd873407a7a5b7c514 |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* set_label_op_params.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: alagache <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/06/01 16:33:31 by alagache #+# #+# */
/* Updated: 2020/06/09 23:04:37 by alagache ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include "asm.h"
#include "libft.h"
#include "ft_printf.h"
#include "manage_error.h"
static void set_label(t_cor *cor)
{
char *ptr;
if ((ptr = ft_strchr(cor->line, LABEL_CHAR)) != NULL
&& ft_strchr(SEP_CHARS, *(ptr - 1)) == NULL)
{
cor->label = cor->line;
while (ft_strchr(WHITESPACE, *(cor->label)) != NULL)
(cor->label)++;
}
}
static int set_op(t_cor *cor)
{
int iterator;
int found;
size_t len_key;
t_op op;
cor->op_str = cor->line;
if (cor->label != NULL)
cor->op_str = ft_strchr(cor->label, ':') + 1;
while (ft_strchr(WHITESPACE, *(cor->op_str)) != NULL)
cor->op_str++;
if (*(cor->op_str) == '\0')
return (NOT_OP);
iterator = NB_OF_INSTRUCTION;
found = 0;
while (found == 0 && --iterator >= 0)
{
op = g_op_tab[iterator];
len_key = ft_strlen(op.keyword);
if (ft_strncmp(cor->op_str, op.keyword, len_key) == 0)
found = 1;
}
cor->op = &(g_op_tab[iterator]);
*(cor->op_str + len_key) = ',';
return (SUCCESS);
}
static int clean_params(t_cor *cor)
{
int iterator;
int jterator;
iterator = 0;
while (++iterator <= cor->op->nbr_arg)
{
if (whitespace(cor->params[iterator - 1],
ft_strlen(cor->params[iterator - 1])) == SUCCESS)
{
ft_dprintf(STDERR_FILENO, EMPTY_ARG);
return (FAILURE);
}
while (ft_strchr(WHITESPACE, *(cor->params[iterator - 1])) != NULL)
(cor->params[iterator - 1])++;
jterator = ft_strlen(cor->params[iterator - 1]);
while (ft_strchr(WHITESPACE, cor->params[iterator - 1][--jterator])
!= NULL)
cor->params[iterator - 1][jterator] = '\0';
}
return (SUCCESS);
}
static int set_params_str(t_cor *cor)
{
int iterator;
iterator = 0;
while (++iterator <= cor->op->nbr_arg)
{
if (iterator == 1)
cor->params[iterator - 1] = ft_strchr(cor->op_str, ',') + 1;
else
cor->params[iterator - 1] =
ft_strchr(cor->params[iterator - 2], ',') + 1;
}
iterator = 0;
while (++iterator <= cor->op->nbr_arg)
*(cor->params[iterator - 1] - 1) = '\0';
if (clean_params(cor) == FAILURE
|| gen_ocp(cor) == FAILURE
|| check_ocp(cor) == FAILURE)
return (FAILURE);
return (SUCCESS);
}
int set_label_op(t_cor *cor)
{
int iterator;
iterator = -1;
while ((cor + (++iterator))->line != NULL)
{
set_label(cor + iterator);
if (set_op(cor + iterator) == SUCCESS)
{
if (set_params_str(cor + iterator) == FAILURE)
return (FAILURE);
}
}
return (SUCCESS);
}
| C | CL | f5c9b869f536ac7b8d3ec2191a2a5907b0eee2df226e14ec377b0cc34576a5e7 |
/**************************************************************************
Copyright:novigo
Author:[email protected]
Date:2016-03-18
Description:
**************************************************************************/
#include "cp_filter.h"
cp_filter_t *cp_filter_create();
/*模块创建接口,表示创建一个模块*/
cp_int32_t init_filter(cp_filter_t *filter, const cp_filter_info_t *filter_info);
/*模块打开运行接口,在模块init之后,会被调用*/
cp_int32_t open_filter(cp_filter_t *filter, const cp_filter_info_t *filter_info);
/*读取模块数据,flag为读取模式的扩展标志。默认为0,其他为预留*/
cp_int32_t read_filter(cp_filter_t *filter, cp_uchar_t **buf, cp_int32_t len, cp_int32_t flag);
/*写模块数据,flag为写模式的扩展标志。默认为0,其他为预留*/
cp_int32_t write_filter(cp_filter_t *filter, const cp_uchar_t **buf, cp_int32_t len, cp_int32_t flag);
/*关闭模块*/
cp_int32_t close_filter(cp_filter_t *filter);
/*退出模块*/
cp_int32_t exit_filter(cp_filter_t *filter);
/*设置模块参数*/
cp_int32_t set_option_filter(cp_filter_t *filter, cp_int32_t optname, const cp_void_t* optval);
cp_int32_t get_option_filter(cp_filter_t *filter, cp_int32_t optname, cp_void_t* optval);
/*模块创建接口,表示创建一个模块*/
cp_int32_t init_filter(cp_filter_t *filter, const cp_filter_info_t *filter_info)
{
return 0;
}
/*模块打开运行接口,在模块init之后,会被调用*/
cp_int32_t open_filter(cp_filter_t *filter, const cp_filter_info_t *filter_info)
{
return 0;
}
/*读取模块数据,flag为读取模式的扩展标志。默认为0,其他为预留*/
cp_int32_t read_filter(cp_filter_t *filter, cp_uchar_t **buf, cp_int32_t len, cp_int32_t flag)
{
return 0;
}
/*写模块数据,flag为写模式的扩展标志。默认为0,其他为预留*/
cp_int32_t write_filter(cp_filter_t *filter, const cp_uchar_t **buf, cp_int32_t len, cp_int32_t flag)
{
return 0;
}
/*关闭模块*/
cp_int32_t close_filter(cp_filter_t *filter)
{
return 0;
}
/*退出模块*/
cp_int32_t exit_filter(cp_filter_t *filter)
{
return 0;
}
/*设置模块参数*/
cp_int32_t set_option_filter(cp_filter_t *filter, cp_int32_t optname, const cp_void_t* optval)
{
return 0;
}
cp_int32_t get_option_filter(cp_filter_t *filter, cp_int32_t optname, cp_void_t* optval)
{
return 0;
}
| C | CL | ed637e222f1c3e710de4544e850ca91f4b3c2b713c5b40ea7d186d0186cea112 |
#include <assert.h>
#include <getopt.h> /* getopt_long() */
#include <unistd.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <asm/types.h> /* for videodev2.h */
#include <pthread.h>
#include <A20V4l2.h>
#define CAMERA_PORTING_DEBUG
#ifdef CAMERA_PORTING_DEBUG
#define CAMERA_DEBUG IRIS_PRINTF
#else
#define CAMERA_DEBUG
#endif
//#define VIDIOC_S_CTRLV2 0xc00c561c //VIDIOC_S_CTRL 0xc008561c
//#define VIDIOC_G_CTRLV2 0xc00c561b
#define V4l2_ClearMemory(buff) memset (&(buff), 0, sizeof (buff))
#define V4L2_PIX_FMT_SGRBG10 v4l2_fourcc('B', 'A', '1', '0') /* 10 GRGR.. BGBG.. */
#define MAX_SHUTTER 5
#define MIN_SHUTTER -5
#define MAX_GAIN 4
#define MIN_GAIN 1
struct FrameSpace {
void * start;
size_t length;
};
struct V4L2_Handle{
int fd;
int frameid;
int gain;
int shutter;
int hflip;
int vflip;
int status;
char name[24];
pthread_mutex_t mutex;
struct FrameSpace* buffers;
};
static int V4l2Ioctl(int fd, int request, void * arg)
{
return ioctl(fd, request, arg);
}
int V4l2_SetParams(void* CamHandle,int index,int value)
{
int ret = 0;
int ret2 = 0;
struct v4l2_control ctrl = {0};
if(CamHandle == NULL)
{
return V4L2_DEV_SUCCESS;
}
struct V4L2_Handle* handle = CamHandle;
if(handle->fd == V4L2_DEV_FAIL)
{
return V4L2_DEV_SUCCESS;
}
switch(index)
{
case 0:
if(value == handle->gain||value<1||value>8)//increase
{
return 2;
}
ctrl.id = V4L2_CID_GAIN;
ctrl.value = value;
ret = V4l2Ioctl(handle->fd, VIDIOC_S_CTRL, &ctrl);
if (V4L2_DEV_SUCCESS != ret)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_S_CTRL 0x%x\n",ret);
return -1;
}
handle->gain = value;
break;
case 1:
if(value > 0)//increase
{
if(handle->shutter == MAX_SHUTTER)
{
return 2;
}
value = handle->shutter+1;
}
else//decrease
{
if(handle->shutter == MIN_SHUTTER)
{
return 2;
}
value = handle->shutter-1;
}
ctrl.id = V4L2_CID_EXPOSURE;
ctrl.value = value;
ret = V4l2Ioctl(handle->fd, VIDIOC_S_CTRL, &ctrl);
//CAMERA_DEBUG(IRIS_PF_DEBUG,"set shutter %d\n",value);
if (V4L2_DEV_SUCCESS != ret)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_S_CTRL 0x%x\n",ret);
return -1;
}
handle->shutter = value;
break;
case 2:
if(handle->hflip == 0)
{
value = 1;
}
else
{
value = 0;
}
ctrl.id = V4L2_CID_HFLIP;
ctrl.value = value;
ret = V4l2Ioctl(handle->fd, VIDIOC_S_CTRL, &ctrl);
if (V4L2_DEV_SUCCESS != ret)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_S_CTRL 0x%x\n",ret);
return -1;
}
handle->hflip = value;
break;
case 3:
if(handle->vflip == 0)
{
value = 1;
}
else
{
value = 0;
}
ctrl.id = V4L2_CID_VFLIP;
ctrl.value = value;
ret = V4l2Ioctl(handle->fd, VIDIOC_S_CTRL, &ctrl);
if (V4L2_DEV_SUCCESS != ret)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_S_CTRL 0x%x\n",ret);
return -1;
}
handle->vflip = value;
break;
case 4:
ctrl.id = V4L2_CID_EXPOSURE;
ctrl.value = value;
ret = V4l2Ioctl(handle->fd, VIDIOC_S_CTRL, &ctrl);
//CAMERA_DEBUG(IRIS_PF_DEBUG,"set shutter %d\n",value);
if (V4L2_DEV_SUCCESS != ret)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_S_CTRL 0x%x\n",ret);
return -1;
}
break;
case 5:
ctrl.id = V4L2_CID_EXPOSURE;
ctrl.value = 0;
ret = V4l2Ioctl(handle->fd, VIDIOC_G_CTRL, &ctrl);
CAMERA_DEBUG(IRIS_PF_DEBUG,"get shutter %d\n",ctrl.value);
if (V4L2_DEV_SUCCESS != ret)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_G_CTRL 0x%x\n",ret);
return -1;
}
ctrl.id = V4L2_CID_EXPOSURE;
ctrl.value += value;
ret = V4l2Ioctl(handle->fd, VIDIOC_S_CTRL, &ctrl);
CAMERA_DEBUG(IRIS_PF_DEBUG,"set shutter %d\n",ctrl.value);
if (V4L2_DEV_SUCCESS != ret)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_S_CTRL 0x%x\n",ret);
return -1;
}
break;
default:
break;
}
return 0;
}
static int V4l2_Mmap(void* CamHandle)
{
struct v4l2_requestbuffers req;
struct v4l2_buffer buf;
int buffers_num = 0;
struct V4L2_Handle* handle = CamHandle;
V4l2_ClearMemory(req);
req.count = MMP_BUF_MAX;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if (V4L2_DEV_SUCCESS != V4l2Ioctl(handle->fd, VIDIOC_REQBUFS, &req))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"requit memory on %s fail\n", handle->name);
return V4L2_DEV_MMFAIL;
}
if (req.count < MMP_BUF_MAX)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"Insufficient buffer memory on %s\n", handle->name);
return V4L2_DEV_MMFAIL;
}
handle->buffers = calloc(req.count, sizeof(struct FrameSpace));
if (handle->buffers == NULL)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"out of memoryl\n");
return V4L2_DEV_MMFAIL;
}
for (buffers_num = 0; buffers_num < req.count; ++buffers_num)
{
V4l2_ClearMemory(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = buffers_num;
if (V4L2_DEV_SUCCESS != V4l2Ioctl(handle->fd, VIDIOC_QUERYBUF, &buf))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"get mmap addr fail\n");
if(handle->buffers!=NULL){
free(handle->buffers);
handle->buffers = NULL;
}
return V4L2_DEV_MMFAIL;
}
handle->buffers[buffers_num].length = buf.length;
handle->buffers[buffers_num].start = mmap(NULL, buf.length,PROT_READ | PROT_WRITE,MAP_SHARED, handle->fd, buf.m.offset);
if (MAP_FAILED == handle->buffers[buffers_num].start)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"mmap fail\n");
return V4L2_DEV_MMFAIL;
}
}
return V4L2_DEV_SUCCESS;
}
int V4l2_StopCapture(struct V4L2_Handle* handle)
{
enum v4l2_buf_type type;
if(handle->status == 0)
{
return V4L2_DEV_SUCCESS;
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (V4L2_DEV_SUCCESS != V4l2Ioctl(handle->fd, VIDIOC_STREAMOFF, &type))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_STREAMON failure!\n");
return V4L2_DEV_FAIL;
}
handle->status = 0;
return V4L2_DEV_SUCCESS;
}
int V4l2_StartCapture(struct V4L2_Handle* handle)
{
unsigned int i;
enum v4l2_buf_type type;
if(handle->status == 1)
{
return V4L2_DEV_SUCCESS;
}
struct v4l2_buffer buf;
for (i = 0; i < MMP_BUF_MAX; ++i)
{
V4l2_ClearMemory (buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if (V4L2_DEV_SUCCESS != V4l2Ioctl(handle->fd, VIDIOC_QBUF, &buf))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_QBUF failure!\n");
return V4L2_DEV_FAIL;
}
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (V4L2_DEV_SUCCESS != V4l2Ioctl(handle->fd, VIDIOC_STREAMON, &type))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_STREAMON failure!\n");
return V4L2_DEV_FAIL;
}
handle->status = 1;
return V4L2_DEV_SUCCESS;
}
int V4l2_OpenDev(unsigned char* name,int cm, void** CamHandle, int with, int high, int rawfmt)
{
int i;
int ret;
struct stat st;
v4l2_std_id std;
unsigned int min;
struct v4l2_capability cap;
struct v4l2_cropcap cropcap;
struct v4l2_crop crop;
struct v4l2_format fmt;
struct v4l2_control ctrl = {0};
struct V4L2_Handle* handle = NULL;
handle = malloc(sizeof(struct V4L2_Handle));
//handle = (struct V4L2_Handle*)CamHandle;
switch(cm)
{
case IRISCAMERA:
handle->shutter = 4;
handle->gain = 2;
handle->hflip = 0;
handle->vflip = 0;
break;
case FACECAMERA:
handle->shutter = 4;
handle->gain = 2;
handle->hflip = 0;
handle->vflip = 0;
break;
case USBCAMERA:
break;
default:
break;
}
*CamHandle = handle;
handle->fd = open(name, O_RDWR, 0);
if (V4L2_DEV_FAIL == handle->fd)
{
if(*CamHandle!=NULL){
free(*CamHandle);
*CamHandle = NULL;
}
CAMERA_DEBUG(IRIS_PF_ERROR,"Open camera failure!\n");
return V4L2_DEV_NOFIX;
}
pthread_mutex_init(&handle->mutex,NULL);
if (V4L2_DEV_SUCCESS != V4l2Ioctl(handle->fd, VIDIOC_QUERYCAP, &cap))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"%s is no V4L2 device\n", handle->name);
close(handle->fd);
pthread_mutex_destroy(&handle->mutex);
if(*CamHandle!=NULL){
free(*CamHandle);
*CamHandle = NULL;
}
return V4L2_DEV_NOFIX;
}
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"%s is no video capture device\n", handle->name);
close(handle->fd);
handle->fd = V4L2_DEV_FAIL;
pthread_mutex_destroy(&handle->mutex);
if(*CamHandle!=NULL){
free(*CamHandle);
*CamHandle = NULL;
}
return V4L2_DEV_FAIL;
}
if (!(cap.capabilities & V4L2_CAP_STREAMING))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"%s does not support streaming i/o\n", handle->name);
close(handle->fd);
handle->fd = V4L2_DEV_FAIL;
pthread_mutex_destroy(&handle->mutex);
if(*CamHandle!=NULL){
free(*CamHandle);
*CamHandle = NULL;
}
return V4L2_DEV_FAIL;
}
CAMERA_DEBUG(IRIS_PF_INFO,"%s set input\n", handle->name);
int index;
if (V4l2Ioctl(handle->fd, VIDIOC_G_INPUT, &index) < 0)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_G_INPUT 0 error!\n");
close(handle->fd);
handle->fd = V4L2_DEV_FAIL;
pthread_mutex_destroy(&handle->mutex);
if(*CamHandle!=NULL){
free(*CamHandle);
*CamHandle = NULL;
}
return V4L2_DEV_FAIL;
}
else {
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_G_INPUT %d success!\n", index);
}
index = 0;
if (V4L2_DEV_SUCCESS != V4l2Ioctl(handle->fd, VIDIOC_S_INPUT, &index))
{
//CAMERA_DEBUG(IRIS_PF_ERROR,"%s set input 0 fail\n", handle->name);
//close(handle->fd);
//handle->fd = V4L2_DEV_FAIL;
//free(CamHandle);
//CamHandle = NULL;
//return V4L2_DEV_FAIL;
}
//////not all capture support crop!!!!!!!
CAMERA_DEBUG(IRIS_PF_DEBUG,"-#-#-#-#-#-#-#-#-#-#-#-#-#-set cropcap\n");
V4l2_ClearMemory (fmt);
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = with;
fmt.fmt.pix.height = high;
switch(rawfmt)
{
case 1:
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
break;
case 2:
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_SBGGR8;
break;
case 3:
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_SGRBG10;
break;
default:
// fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_SBGGR8;
break;
}
fmt.fmt.pix.field = V4L2_FIELD_NONE;
CAMERA_DEBUG(IRIS_PF_DEBUG,"-#-#-#-#-#-#-#-#-#-#-#-#-#-\n");
CAMERA_DEBUG(IRIS_PF_DEBUG,"=====will set fmt to (%d, %d)--", fmt.fmt.pix.width, fmt.fmt.pix.height);
ret = V4l2Ioctl(handle->fd, VIDIOC_S_FMT, &fmt);
if (V4L2_DEV_SUCCESS != ret)
{
CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_S_FMT 0x%x\n",ret);
close(handle->fd);
handle->fd = V4L2_DEV_FAIL;
pthread_mutex_destroy(&handle->mutex);
if(*CamHandle!=NULL){
free(*CamHandle);
*CamHandle = NULL;
}
return V4L2_DEV_FAIL;
}
if(V4l2_Mmap(handle) != V4L2_DEV_SUCCESS)
{
for (i = 0; i < MMP_BUF_MAX; ++i)
{
if (V4L2_DEV_FAIL== munmap(handle->buffers[i].start, handle->buffers[i].length))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"free map failure!\n");
}
}
if(handle->buffers!=NULL){
free(handle->buffers);
handle->buffers = NULL;
}
close(handle->fd);
handle->fd = V4L2_DEV_FAIL;
pthread_mutex_destroy(&handle->mutex);
if(*CamHandle!=NULL){
free(*CamHandle);
*CamHandle = NULL;
}
return V4L2_DEV_MMFAIL;
}
if(V4l2_StartCapture(handle) != V4L2_DEV_SUCCESS)
{
for (i = 0; i < MMP_BUF_MAX; ++i)
{
if (V4L2_DEV_FAIL== munmap(handle->buffers[i].start, handle->buffers[i].length))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"free map failure!\n");
}
}
if(handle->buffers!=NULL){
free(handle->buffers);
}
close(handle->fd);
pthread_mutex_destroy(&handle->mutex);
handle->fd = V4L2_DEV_FAIL;
if(*CamHandle!=NULL){
free(*CamHandle);
*CamHandle = NULL;
}
return V4L2_DEV_STREAMONFAIL;
}
return V4L2_DEV_SUCCESS;
}
int V4l2_CloseDev(void* CamHandle)
{
unsigned int i;
if(CamHandle == NULL)
{
return V4L2_DEV_SUCCESS;
}
struct V4L2_Handle* handle = CamHandle;
if(handle->fd == V4L2_DEV_FAIL)
{
return V4L2_DEV_SUCCESS;
}
V4l2_StopCapture(handle);
for (i = 0; i < MMP_BUF_MAX; ++i)
{
if (V4L2_DEV_FAIL== munmap(handle->buffers[i].start, handle->buffers[i].length))
{
CAMERA_DEBUG(IRIS_PF_ERROR,"free map failure!\n");
}
}
if(handle->buffers!=NULL){
free(handle->buffers);
handle->buffers = NULL;
}
close(handle->fd);
pthread_mutex_destroy(&handle->mutex);
if(CamHandle!=NULL){
free(CamHandle);
CamHandle = NULL;
}
return V4L2_DEV_SUCCESS;
}
int V4l2_ReadFrame(void* CamHandle,void** buff,int* lenght)
{
struct v4l2_buffer buf;
struct V4L2_Handle* handle = CamHandle;
pthread_mutex_lock(&handle->mutex);
handle->frameid = 0xff;
if(handle->fd == V4L2_DEV_FAIL)
{
pthread_mutex_unlock(&handle->mutex);
return V4L2_DEV_READERROR;
}
if(handle->status == 0)
{
pthread_mutex_unlock(&handle->mutex);
return -2;
}
V4l2_ClearMemory (buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if (V4L2_DEV_FAIL== V4l2Ioctl(handle->fd, VIDIOC_DQBUF, &buf))
{
//perror("de-queue buffers failed");
//CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_DQBUF FAIL!\n");
pthread_mutex_unlock(&handle->mutex);
return V4L2_DEV_READERROR;
}
handle->frameid= buf.index;
*buff = handle->buffers[handle->frameid].start;
*lenght = handle->buffers[handle->frameid].length;
//CAMERA_DEBUG(IRIS_PF_INFO,"get frame %d\n",*lenght);
pthread_mutex_unlock(&handle->mutex);
return V4L2_DEV_SUCCESS;
}
int V4l2_FinishFrame(void* CamHandle)
{
struct v4l2_buffer buf;
struct V4L2_Handle* handle = CamHandle;
pthread_mutex_lock(&handle->mutex);
if(handle->frameid == 0xff)
{
pthread_mutex_unlock(&handle->mutex);
return V4L2_DEV_READFINISHFAIL;
}
V4l2_ClearMemory (buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = handle->frameid;
if (V4L2_DEV_FAIL == V4l2Ioctl(handle->fd, VIDIOC_QBUF, &buf))
{
//CAMERA_DEBUG(IRIS_PF_ERROR,"VIDIOC_QBUF FAIL!\n");
pthread_mutex_unlock(&handle->mutex);
return V4L2_DEV_READFINISHFAIL;
}
//CAMERA_DEBUG(IRIS_PF_INFO,"VIDIOC_QBUF SUCCESS!\n");
pthread_mutex_unlock(&handle->mutex);
return V4L2_DEV_SUCCESS;
}
int
covertoraw(unsigned char* src,unsigned char* dst,int w,int h,int stride)
{
unsigned char *lineBuf;
int hi,wi;
int si = w/4;
int li = w%4;
unsigned char byte0;
unsigned char byte1;
unsigned char byte2;
unsigned char byte3;
unsigned char byte4;
unsigned char byte5;
for(hi=0;hi<h;hi++)
{
lineBuf = src + hi * stride;
for(wi=0;wi<si;wi++) //(byte0 + ((byte1 & 0x3) << 8)
{
byte0 = *(lineBuf++);
byte1 = *(lineBuf++);
byte2 = *(lineBuf++);
byte3 = *(lineBuf++);
byte4 = *(lineBuf++);
*(dst++) = (byte0 +((byte1 & 0x3) << 8))>>2;
*(dst++) = (((byte1 & 0xFC) >> 2)+(((byte2 & 0xf) << 6)))>>2;
*(dst++) = (((byte2 & 0xf0) >> 4)+((byte3 & 0x3f) << 4))>>2;
*(dst++) = (((byte3 & 0xc0) >> 6)+(byte4 << 2))>>2;
}
if (li != 0)
{
switch(li)
{
case 1:
byte0 = *(lineBuf++);
byte1 = *(lineBuf++);
*(dst++) = (byte0 +((byte1 & 0x3) << 8))>>2;
break;
case 2:
byte0 = *(lineBuf++);
byte1 = *(lineBuf++);
byte2 = *(lineBuf++);
*(dst++) = (byte0 +((byte1 & 0x3) << 8))>>2;
*(dst++) = ((byte1 & 0xFC) >> 2)+((byte2 & 0xf) << 6)>>2;
break;
case 3:
byte0 = *(lineBuf++);
byte1 = *(lineBuf++);
byte2 = *(lineBuf++);
byte3 = *(lineBuf++);
*(dst++) = (byte0 +((byte1 & 0x3) << 8))>>2;
*(dst++) = (((byte1 & 0xFC) >> 2)+((byte2 & 0xf) << 6))>>2;
*(dst++) = (((byte2 & 0xf0) >> 4)+((byte3 & 0x3f) << 4))>>2;
break;
}
}
}
return 0;
}
int
cover10toraw8(unsigned char* src,unsigned char* dst,int w,int h,int stride)
{
unsigned char *lineBuf;
int hi,wi;
int si = w/4;
int li = w%4;
unsigned char byte0;
unsigned char byte1;
unsigned char byte2;
unsigned char byte3;
unsigned char byte4;
unsigned char byte5;
unsigned char byte6;
unsigned char byte7;
for(hi=h-1;hi>=0;hi--)
{
lineBuf = src + hi * stride;
for(wi=0;wi<si;wi++)
{
byte0 = *(lineBuf++);
byte1 = *(lineBuf++);
byte2 = *(lineBuf++);
byte3 = *(lineBuf++);
byte4 = *(lineBuf++);
byte5 = *(lineBuf++);
byte6 = *(lineBuf++);
byte7 = *(lineBuf++);
*(dst++) = ((byte0>>2)&0x3F) + ((byte1<<6) & 0xC0);
*(dst++) = ((byte2>>2)&0x3F) + ((byte3<<6) & 0xC0);
*(dst++) = ((byte4>>2)&0x3F) + ((byte5<<6) & 0xC0);
*(dst++) = ((byte6>>2)&0x3F) + ((byte7<<6) & 0xC0);
}
switch(li)
{
case 1:
byte0 = *(lineBuf++);
byte1 = *(lineBuf++);
((byte0>>2)&0x3F) + ((byte1<<6) & 0xC0);
break;
case 2:
byte0 = *(lineBuf++);
byte1 = *(lineBuf++);
byte2 = *(lineBuf++);
byte3 = *(lineBuf++);
*(dst++) = ((byte0>>2)&0x3F) + ((byte1<<6) & 0xC0);
*(dst++) = ((byte2>>2)&0x3F) + ((byte3<<6) & 0xC0);
break;
case 3:
byte0 = *(lineBuf++);
byte1 = *(lineBuf++);
byte2 = *(lineBuf++);
byte3 = *(lineBuf++);
byte4 = *(lineBuf++);
byte5 = *(lineBuf++);
*(dst++) = ((byte0>>2)&0x3F) + ((byte1<<6) & 0xC0);
*(dst++) = ((byte2>>2)&0x3F) + ((byte3<<6) & 0xC0);
*(dst++) = ((byte4>>2)&0x3F) + ((byte5<<6) & 0xC0);
break;
default:
break;
}
}
return 0;
}
int
cover10toraw8_2(unsigned char* src,unsigned char* dst,int w,int h,int stride)
{
unsigned char *lineBuf;
int hi,wi;
unsigned char byte0;
for(hi=h*2 - 2;hi>=0;hi-=2)
{
lineBuf = src + hi * stride;
for(wi = 0;wi < w;wi++)
{
*(dst++) = *(lineBuf++);
}
}
return 0;
}
int SaveFile(char* filename,unsigned char* bmp,int w ,int h,int position)
{
int i = 0;
char color = 0;
char end[2] = {0,0};
char patte[1024] = {0};
int pos = 0;
char file[400] = {0};
time_t now;
struct timeval tv;
struct tm *timenow;
FILE *outfile;
char heard[54] = {0x42,0x4d,0x30,0x0C,0x01,0,0,0,0,0,0x36,4,0,0,0x28,0,\
0,0,0xF5,0,0,0,0x46,0,0,0,0x01,0,8,0,0,0,\
0,0,0xF8,0x0b,0x01,0,0x12,0x0b,0,0,0x12,0x0b,0,0,0,0,\
0,0,0,0,0,0};
int size = w*h;
int allsize = size +1080;
heard[2] = allsize&0xFF;
heard[3] = (allsize>>8)&0xFF;
heard[4] = (allsize>>16)&0xFF;
heard[5] = (allsize>>24)&0xFF;
heard[18] = w&0xFF;
heard[19] = (w>>8)&0xFF;
heard[20] = (w>>16)&0xFF;
heard[21] = (w>>24)&0xFF;
heard[22] = h&0xFF;
heard[23] = (h>>8)&0xFF;
heard[24] = (h>>16)&0xFF;
heard[25] = (h>>24)&0xFF;
allsize -=1078;
heard[34] = allsize&0xFF;
heard[35] = (allsize>>8)&0xFF;
heard[36] = (allsize>>16)&0xFF;
heard[37] = (allsize>>24)&0xFF;
for(i=0;i<1024;i+=4)
{
patte[pos++] = color;
patte[pos++] = color;
patte[pos++] = color;
patte[pos++] = 0;
color++;
}
time(&now);
timenow = localtime(&now);
gettimeofday(&tv, NULL);
sprintf(file,"%s/%d__%04d-%02d-%02d_%02d-%02d-%02d_%06d.raw",filename,position,timenow->tm_year+1900,timenow->tm_mon+1,timenow->tm_mday,timenow->tm_hour,timenow->tm_min,timenow->tm_sec,tv.tv_usec);
outfile = fopen( file, "w" );
if(outfile!=NULL){
fwrite(bmp,size,1,outfile);
fclose(outfile);
}
}
int GetPrivewFrame(void* CamHandle,unsigned char* yuv,int CamFmt)
{
unsigned char* Frame;
int LenL;
int in = 0;
int timout = 0;
static int tmd = 0;
if(CamHandle == NULL)
{
return -1;
}
while(timout < 4)
{
if(V4l2_ReadFrame(CamHandle,(void**)&Frame,&LenL) == V4L2_DEV_SUCCESS)
{
switch(CamFmt)
{
case 1:
memcpy(yuv,Frame,LenL);
break;
case 2:
memcpy(yuv,Frame,LenL);
break;
case 3:
CAMERA_DEBUG(IRIS_PF_INFO,"get frame %d!\n",LenL);
//cover10toraw8(Frame,yuv,1920,1080,3840);
cover10toraw8_2(Frame,yuv,1920,1080,1920);
tmd++;
if(tmd == 50)
{
//SaveFile("/sdcard/sykean",Frame,3840 ,1080,3);
SaveFile("/sdcard/sykean",Frame,3840 ,1080,3);
}
break;
}
V4l2_FinishFrame(CamHandle);
return 0;
}
else
{
timout++;
usleep(20000);
continue;
}
}
return -1;
}
int ClearAllFrame(void* CamHandle)
{
unsigned char* Frame;
int Lenght;
int i = 0;
if(CamHandle == NULL)
{
return 0;
}
for(i =0;i<MMP_BUF_MAX;)
{
if(V4l2_ReadFrame(CamHandle,(void**)&Frame,&Lenght) == V4L2_DEV_SUCCESS)
{
V4l2_FinishFrame(CamHandle);
i++;
}
else
{
usleep(30000);
}
}
return 0;
}
| C | CL | 0589df94e8eec16d75fc6c034bd58a1c09107cbbb4cc6714545b4ea5c498ccca |
/*******************************************************************************
* File Name: Green.h
* Version 1.90
*
* Description:
* This file containts Control Register function prototypes and register defines
*
* Note:
*
********************************************************************************
* Copyright 2008-2012, Cypress Semiconductor Corporation. All rights reserved.
* You may use this file only in accordance with the license, terms, conditions,
* disclaimers, and limitations in the end user license agreement accompanying
* the software package with which this file was provided.
*******************************************************************************/
#if !defined(CY_PINS_Green_H) /* Pins Green_H */
#define CY_PINS_Green_H
#include "cytypes.h"
#include "cyfitter.h"
#include "cypins.h"
#include "Green_aliases.h"
/* Check to see if required defines such as CY_PSOC5A are available */
/* They are defined starting with cy_boot v3.0 */
#if !defined (CY_PSOC5A)
#error Component cy_pins_v1_90 requires cy_boot v3.0 or later
#endif /* (CY_PSOC5A) */
/* APIs are not generated for P15[7:6] */
#if !(CY_PSOC5A &&\
Green__PORT == 15 && ((Green__MASK & 0xC0) != 0))
/***************************************
* Function Prototypes
***************************************/
void Green_Write(uint8 value) ;
void Green_SetDriveMode(uint8 mode) ;
uint8 Green_ReadDataReg(void) ;
uint8 Green_Read(void) ;
uint8 Green_ClearInterrupt(void) ;
/***************************************
* API Constants
***************************************/
/* Drive Modes */
#define Green_DM_ALG_HIZ PIN_DM_ALG_HIZ
#define Green_DM_DIG_HIZ PIN_DM_DIG_HIZ
#define Green_DM_RES_UP PIN_DM_RES_UP
#define Green_DM_RES_DWN PIN_DM_RES_DWN
#define Green_DM_OD_LO PIN_DM_OD_LO
#define Green_DM_OD_HI PIN_DM_OD_HI
#define Green_DM_STRONG PIN_DM_STRONG
#define Green_DM_RES_UPDWN PIN_DM_RES_UPDWN
/* Digital Port Constants */
#define Green_MASK Green__MASK
#define Green_SHIFT Green__SHIFT
#define Green_WIDTH 1u
/***************************************
* Registers
***************************************/
/* Main Port Registers */
/* Pin State */
#define Green_PS (* (reg8 *) Green__PS)
/* Data Register */
#define Green_DR (* (reg8 *) Green__DR)
/* Port Number */
#define Green_PRT_NUM (* (reg8 *) Green__PRT)
/* Connect to Analog Globals */
#define Green_AG (* (reg8 *) Green__AG)
/* Analog MUX bux enable */
#define Green_AMUX (* (reg8 *) Green__AMUX)
/* Bidirectional Enable */
#define Green_BIE (* (reg8 *) Green__BIE)
/* Bit-mask for Aliased Register Access */
#define Green_BIT_MASK (* (reg8 *) Green__BIT_MASK)
/* Bypass Enable */
#define Green_BYP (* (reg8 *) Green__BYP)
/* Port wide control signals */
#define Green_CTL (* (reg8 *) Green__CTL)
/* Drive Modes */
#define Green_DM0 (* (reg8 *) Green__DM0)
#define Green_DM1 (* (reg8 *) Green__DM1)
#define Green_DM2 (* (reg8 *) Green__DM2)
/* Input Buffer Disable Override */
#define Green_INP_DIS (* (reg8 *) Green__INP_DIS)
/* LCD Common or Segment Drive */
#define Green_LCD_COM_SEG (* (reg8 *) Green__LCD_COM_SEG)
/* Enable Segment LCD */
#define Green_LCD_EN (* (reg8 *) Green__LCD_EN)
/* Slew Rate Control */
#define Green_SLW (* (reg8 *) Green__SLW)
/* DSI Port Registers */
/* Global DSI Select Register */
#define Green_PRTDSI__CAPS_SEL (* (reg8 *) Green__PRTDSI__CAPS_SEL)
/* Double Sync Enable */
#define Green_PRTDSI__DBL_SYNC_IN (* (reg8 *) Green__PRTDSI__DBL_SYNC_IN)
/* Output Enable Select Drive Strength */
#define Green_PRTDSI__OE_SEL0 (* (reg8 *) Green__PRTDSI__OE_SEL0)
#define Green_PRTDSI__OE_SEL1 (* (reg8 *) Green__PRTDSI__OE_SEL1)
/* Port Pin Output Select Registers */
#define Green_PRTDSI__OUT_SEL0 (* (reg8 *) Green__PRTDSI__OUT_SEL0)
#define Green_PRTDSI__OUT_SEL1 (* (reg8 *) Green__PRTDSI__OUT_SEL1)
/* Sync Output Enable Registers */
#define Green_PRTDSI__SYNC_OUT (* (reg8 *) Green__PRTDSI__SYNC_OUT)
#if defined(Green__INTSTAT) /* Interrupt Registers */
#define Green_INTSTAT (* (reg8 *) Green__INTSTAT)
#define Green_SNAP (* (reg8 *) Green__SNAP)
#endif /* Interrupt Registers */
#endif /* CY_PSOC5A... */
#endif /* CY_PINS_Green_H */
/* [] END OF FILE */
| C | CL | e8b68adb611323923aca9fec6804eaac4b4737ecc8ae42af63ef40dab01b7fa0 |
// TO-DO:
// * hook up with RL -- needs ANN for Q
// * the calculation of "error" in back-prop is unclear
// TO-DO: (Cantonese task)
// * need vector representation for individual words
// TODO (yky#1#): There is a convergence problem -- it almost always converges and really quickly
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <assert.h>
#include <time.h>
#include "RNN.h"
// #define DATASIZE 800 // size of training data and test data
#define ETA 0.01 // learning rate
#define BIASOUTPUT 1 // output for bias. It's always 1.
#define MAX_EPOCHS 20 // maximum epochs
#define RECURRENCE 10 // RNN acts on K n times
//********sigmoid function and randomWeight generator********************//
double sigmoid(double v)
{ return 1 / (1 + exp(-v)) - 0.5; }
double randomWeight() // generate random weight between [+2,-2]
{ return (rand() / (float) RAND_MAX) * 4.0 - 2.0; }
//****************************create neuron network*********************//
void create_NN(NNET *net, int numLayers, int *neuronsOfLayer)
{
//in order to create a neural network,
//we need know how many layers and how many neurons in each layer
int i, j, k;
srand(time(NULL));
net->numLayers = numLayers;
assert(numLayers >= 3);
net->layers = (LAYER *)malloc(numLayers * sizeof(LAYER));
//construct input layer, no weights
net->layers[0].numNeurons = neuronsOfLayer[0];
net->layers[0].neurons = (NEURON *) malloc(neuronsOfLayer[0] * sizeof(NEURON));
//construct hidden layers
for(i = 1; i < numLayers; i++) //construct layers
{
net->layers[i].neurons = (NEURON *) malloc(neuronsOfLayer[i] * sizeof(NEURON));
net->layers[i].numNeurons = neuronsOfLayer[i];
for(j = 0; j < neuronsOfLayer[i]; j++) // construct each neuron in the layer
{
net->layers[i].neurons[j].weights = (double *)malloc((neuronsOfLayer[i - 1] + 1) * sizeof(double));
for(k = 0; k <= neuronsOfLayer[i - 1]; k++)
{
//construct weights of neuron from previous layer neurons
net->layers[i].neurons[j].weights[k] = randomWeight(); //when k = 0, it's bias weight
//net->layers[i].neurons[j].weights[k] = 0;
}
}
}
}
//**************************** forward-propagation ***************************//
void forward_prop(NNET *net, int dim_V, double V[])
{
//set the output of input layer
//two inputs x1 and x2
for (int i = 0; i < dim_V; ++i)
net->layers[0].neurons[i].output = V[i];
//calculate output from hidden layers to output layer
for (int i = 1; i < net->numLayers; i++)
{
for (int j = 0; j < net->layers[i].numNeurons; j++)
{
double v = 0; //induced local field for neurons
//calculate v, which is the sum of the product of input and weights
for (int k = 0; k <= net->layers[i - 1].numNeurons; k++)
{
if (k == 0)
v += net->layers[i].neurons[j].weights[k] * BIASOUTPUT;
else
v += net->layers[i].neurons[j].weights[k] * net->layers[i - 1].neurons[k - 1].output;
}
// For the last layer, skip the sigmoid function
if (i == net->numLayers - 1)
net->layers[i].neurons[j].output = v;
else
net->layers[i].neurons[j].output = sigmoid(v);
}
}
}
#define LastLayer (net->layers[numLayers - 1])
// Calculate error between output of forward-prop and a given answer Y
double calc_error(NNET *net, double Y[])
{
// calculate mean square error;
// desired value = K* = trainingOUT
double sumOfSquareError = 0;
int numLayers = net->numLayers;
// This means each output neuron corresponds to a classification label --YKY
for (int i = 0; i < LastLayer.numNeurons; i++)
{
//error = desired_value - output
double error = Y[i] - LastLayer.neurons[i].output;
LastLayer.neurons[i].error = error;
sumOfSquareError += error * error / 2;
}
double mse = sumOfSquareError / LastLayer.numNeurons;
return mse; //return the root of mean square error
}
//**************************backpropagation***********************//
#define LastLayer (net->layers[numLayers - 1])
void back_prop(NNET *net)
{
//calculate delta
int i, j, k;
int numLayers = net->numLayers;
//calculate delta for output layer
for (i = 0; i < LastLayer.numNeurons; i++)
{
double output = LastLayer.neurons[i].output;
double error = LastLayer.neurons[i].error;
//for output layer, delta = y(1-y)error
LastLayer.neurons[i].delta = output * (1 - output) * error;
}
//calculate delta for hidden layers
for (i = numLayers - 2; i > 0; i--)
{
for (j = 0; j < net->layers[i].numNeurons; j++)
{
double output = net->layers[i].neurons[j].output;
double sum = 0;
for (k = 0 ; k < net->layers[i + 1].numNeurons; k++)
{
sum += net->layers[i + 1].neurons[k].weights[j + 1] * net->layers[i + 1].neurons[k].delta;
}
net->layers[i].neurons[j].delta = output * (1 - output) * sum;
}
}
//update weights
for (i = 1; i < numLayers; i++)
{
for (j = 0; j < net->layers[i].numNeurons; j++)
{
for (k = 0; k <= net->layers[i - 1].numNeurons; k++)
{
double inputForThisNeuron;
if (k == 0)
inputForThisNeuron = 1; //bias input
else
inputForThisNeuron = net->layers[i - 1].neurons[k - 1].output;
net->layers[i].neurons[j].weights[k] += ETA * net->layers[i].neurons[j].delta * inputForThisNeuron;
}
}
}
}
//*************************calculate error average*************//
// relative error = |average of second 10 errors : average of first 10 errors - 1|
// It is 0 if the errors stay constant, non-zero if the errors are changing rapidly
// these errors are from the training set --YKY
double relative_error(double error[], int len)
{
len = len - 1;
if (len < 20)
return 1;
//keep track of the last 20 Root of Mean Square Errors
int start1 = len - 20;
int start2 = len - 10;
double error1, error2 = 0;
//calculate the average of the first 10 errors
for (int i = start1; i < start1 + 10; i++)
error1 += error[i];
double averageError1 = error1 / 10;
//calculate the average of the second 10 errors
for (int i = start2; i < start2 + 10; i++)
error2 += error[i];
double averageError2 = error2 / 10;
double relativeErr = (averageError1 - averageError2) / averageError1;
return (relativeErr > 0) ? relativeErr : -relativeErr;
}
| C | CL | 6c2e208d644b759f312a64e7bafff5e91e9a533deb3ebdc7005497c0d9182cb7 |
/*
* Write a program to check a C program for rudimentary syntax errors like
* unmatched parentheses, brackets and braces. Don't forget about quotes, both
* single and double, escape sequences, and comments. (This program is hard if
* you do it in full generality.)
*/
#include <stdio.h>
main()
{
| C | CL | 00408efe8d9d2850de44d79dce3bb06a65330c312213ce519e2d40a0f5f2d040 |
typedef struct _DOUBLE_LIKE_NODE
{
int data;
struct _DOUBLE_LIKE_NODE *prev;
struct _DOUBLE_LIKE_NODE *next;
} DOUBLE_LIKE_NODE;
typedef int STATUS; // 0 fail , 1 success
DOUBLE_LIKE_NODE* create_double_link_node(int value);
STATUS insert_data_into_double_link(DOUBLE_LIKE_NODE **ppDLinkNode, int data);
STATUS switch_double_link_node(DOUBLE_LIKE_NODE *pDLinkNode, int pos);
void print_double_link_node(const DOUBLE_LIKE_NODE *pDLinkNode);
| C | CL | 30ddd4eb037224d636a1e7ce3ba272316df9a144b12747a00097c05acc00935e |
/*
Data value and formatted write programs
Copyright (c) 2016, 2017. Francis G. McCabe
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
*/
#include <stdlib.h>
#include <limits.h>
#include "lo.h"
#include "term.h"
#include "tpl.h"
/*
* write a cell in a basic format
* The depth argument limits the depth that tuples are printed to
*/
retCode wStringChr(ioPo f, codePoint ch) {
switch (ch) {
case '\a':
return outStr(f, "\\a");
case '\b':
return outStr(f, "\\b");
case '\x7f':
return outStr(f, "\\d");
case '\x1b':
return outStr(f, "\\e");
case '\f':
return outStr(f, "\\f");
case '\n':
return outStr(f, "\\n");
case '\r':
return outStr(f, "\\r");
case '\t':
return outStr(f, "\\t");
case '\v':
return outStr(f, "\\v");
case '\\':
return outStr(f, "\\\\");
case '\"':
return outStr(f, "\\\"");
default:
if (ch < ' ')
return outMsg(f, "\\+%x;", ch);
else
return outChar(f, ch);
}
}
static retCode outC(ioPo f, ptrPo x, long depth, int prec, logical alt);
retCode outCell(ioPo f, ptrPo x, long depth, int prec, logical alt) {
if (x != NULL)
return outC(f, x, depth, prec, alt);
else
return outStr(f, "(NULL)");
}
static retCode outC(ioPo f, ptrPo x, long depth, int prec, logical alt) {
ptrI vx = *(x = deRef(x));
objPo p = objV(vx);
retCode r = Ok;
switch (ptg(vx)) {
case varTg:
if (isSuspVar((ptrPo) vx))
r = outMsg(f, "_*%x", vx);
else
r = outMsg(f, "_%x", vx);
break;
case objTg: {
ptrI class = p->class;
if (isfwd(class)) {
outMsg(f, "*");
class = *((ptrPo) objV(class));
}
if (class == integerClass)
r = outInteger(f, integerVal((integerPo) p), 10, 0, prec, ' ', False, "", False);
else if (class == floatClass)
r = outFloat(f, floatVal((floatPo) p));
else if (class == stringClass) {
strBuffPo str = (strBuffPo)p;
long pos = 0;
long end = stringLen(str);
char * src = stringVal(str);
r = outChar(f, '\"');
while (pos < end) {
codePoint ch;
r = nxtPoint(src, &pos, end, &ch);
if (r == Ok)
r = wStringChr(f, ch);
}
if (r == Ok)
r = outChar(f, '\"');
} else if (class == classClass) {
clssPo cl = (clssPo) p;
char * clName = className(cl);
r = outText(f, clName, uniStrLen(clName));
if (r == Ok)
r = outChar(f, '/');
if (r == Ok)
r = outInteger(f, classArity(cl), 10, 0, prec, ' ', False, "", False);
} else if (class == consClass) {
if (depth > 0) {
long maxLen = (prec != 0 ? prec * 2 : INT_MAX); /* How many elements to show */
r = outChar(f, '[');
while (r == Ok && IsList(vx)) {
ptrPo ll = listHead(objV(vx));
r = outC(f, ll++, depth - 1, prec, alt);
vx = deRefI(ll);
if (r == Ok && IsList(vx)) {
if (maxLen-- <= 0) {
r = outStr(f, "..."); /* only show a certain length */
goto exit_list; /* what a hack, need a double break */
} else
r = outChar(f, ',');
}
}
if (r == Ok && !IsNil(vx)) {
r = outStr(f, ",..");
if (r == Ok)
r = outC(f, &vx, depth - 1, prec, alt);
}
exit_list:
if (r == Ok)
r = outStr(f, "]");
} else
r = outStr(f, "[...]");
} else if (isTupleClass(class)) {
if (depth > 0) {
char *sep = "";
outChar(f, '(');
long arity = tupleArity(p);
for (long ix = 0; ix < arity; ix++) {
r = outStr(f, sep);
sep = ", ";
if (r == Ok)
r = outC(f, nthArg(p, ix), depth - 1, prec, alt);
}
if (r == Ok)
r = outChar(f, ')');
} else
r = outStr(f, "(...)");
} else if (IsTermClass(class)) {
char * name = objectClassName(p);
r = outMsg(f, "%U", name);
if (depth > 0) {
long arity = objectArity(p);
if (arity > 0) {
ptrPo a = objectArgs(p);
long i;
char *sep = "";
outChar(f, '(');
for (i = 0; r == Ok && i < arity; i++, a++) {
r = outStr(f, sep);
sep = ", ";
if (r == Ok)
r = outC(f, a, depth - 1, prec, alt);
}
if (r == Ok)
r = outChar(f, ')');
}
} else
r = outStr(f, "(...)");
} else if (IsSpecialClass(class)) {
specialClassPo sClass = (specialClassPo) objV(class);
r = sClass->outFun(sClass, f, p);
}
return r;
}
case fwdTg: { /* special case to help with debugging */
outMsg(f, "[0x%x]-->", x);
return outC(f, (ptrPo) p, depth - 1, prec, alt);
}
default:
outMsg(f, "illegal cell found at [%x]", p);
return Error;
}
return r;
}
void dc(ptrPo trm) {
if (trm != NULL)
outMsg(logFile, "0x%x -> %,20w\n", trm, trm);
else
outMsg(logFile, "NULL\n");
flushFile(logFile);
}
void dO(objPo trm) {
ptrI T = objP(trm);
outMsg(logFile, "0x%x : %,20w\n", trm, &T);
flushFile(logFile);
}
| C | CL | a9f04e3fd1659368f4e7a43891620b481e74f67231382809183b3acb30b51288 |
/* Copyright 2020 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "chipset.h"
#include "console.h"
#include "peci.h"
#include "peci_customization.h"
#include "timer.h"
#include "util.h"
/* Console output macros */
#define CPUTS(outstr) cputs(CC_THERMAL, outstr)
#define CPRINTS(format, args...) cprints(CC_THERMAL, format, ## args)
/*****************************************************************************/
/* Internal functions */
int peci_Rd_Pkg_Config(uint8_t index, uint16_t parameter, int rlen, uint8_t *in)
{
int rv;
uint8_t out[PECI_RD_PKG_CONFIG_WRITE_LENGTH];
struct peci_data peci = {
.cmd_code = PECI_CMD_RD_PKG_CFG,
.addr = PECI_TARGET_ADDRESS,
.w_len = PECI_RD_PKG_CONFIG_WRITE_LENGTH,
.r_len = rlen,
.w_buf = out,
.r_buf = in,
.timeout_us = PECI_RD_PKG_CONFIG_TIMEOUT_US,
};
out[0] = 0x00; /* host ID */
out[1] = index;
out[2] = (parameter & 0xff);
out[3] = ((parameter >> 8) & 0xff);
rv = peci_transaction(&peci);
if (rv)
return rv;
return EC_SUCCESS;
}
int peci_Wr_Pkg_Config(uint8_t index, uint16_t parameter, uint32_t data, int wlen)
{
int rv;
int clen;
uint8_t in[PECI_WR_PKG_CONFIG_READ_LENGTH] = {0};
uint8_t out[PECI_WR_PKG_CONFIG_WRITE_LENGTH_DWORD] = {0};
struct peci_data peci = {
.cmd_code = PECI_CMD_WR_PKG_CFG,
.addr = PECI_TARGET_ADDRESS,
.w_len = wlen,
.r_len = PECI_WR_PKG_CONFIG_READ_LENGTH,
.w_buf = out,
.r_buf = in,
.timeout_us = PECI_WR_PKG_CONFIG_TIMEOUT_US,
};
out[0] = 0x00; /* host ID */
out[1] = index;
out[2] = (parameter & 0xff);
out[3] = ((parameter >> 8) & 0xff);
for (clen = 4; clen < wlen - 1; clen++)
out[clen] = ((data >> ((clen - 4) * 8)) & 0xFF);
rv = peci_transaction(&peci);
if (rv)
return rv;
return EC_SUCCESS;
}
/*****************************************************************************/
/* External functions */
int peci_update_PL1(int watt)
{
int rv;
uint32_t data;
if (!chipset_in_state(CHIPSET_STATE_ON))
return EC_ERROR_NOT_POWERED;
data = PECI_PL1_CONTROL_TIME_WINDOWS | PECI_PL1_POWER_LIMIT_ENABLE |
PECI_PL1_POWER_LIMIT(watt);
rv = peci_Wr_Pkg_Config(PECI_INDEX_POWER_LIMITS_PL1, PECI_PARAMS_POWER_LIMITS_PL1,
data, PECI_WR_PKG_CONFIG_WRITE_LENGTH_DWORD);
if (rv)
return rv;
return EC_SUCCESS;
}
int peci_update_PL2(int watt)
{
int rv;
uint32_t data;
if (!chipset_in_state(CHIPSET_STATE_ON))
return EC_ERROR_NOT_POWERED;
data = PECI_PL2_CONTROL_TIME_WINDOWS | PECI_PL2_POWER_LIMIT_ENABLE |
PECI_PL2_POWER_LIMIT(watt);
rv = peci_Wr_Pkg_Config(PECI_INDEX_POWER_LIMITS_PL2, PECI_PARAMS_POWER_LIMITS_PL2,
data, PECI_WR_PKG_CONFIG_WRITE_LENGTH_DWORD);
if (rv)
return rv;
return EC_SUCCESS;
}
int peci_update_PL4(int watt)
{
int rv;
uint32_t data;
if (!chipset_in_state(CHIPSET_STATE_ON))
return EC_ERROR_NOT_POWERED;
data = PECI_PL4_POWER_LIMIT(watt);
rv = peci_Wr_Pkg_Config(PECI_INDEX_POWER_LIMITS_PL4, PECI_PARAMS_POWER_LIMITS_PL4,
data, PECI_WR_PKG_CONFIG_WRITE_LENGTH_DWORD);
if (rv)
return rv;
return EC_SUCCESS;
}
int peci_update_PsysPL2(int watt)
{
int rv;
uint32_t data;
if (!chipset_in_state(CHIPSET_STATE_ON))
return EC_ERROR_NOT_POWERED;
data = PECI_PSYS_PL2_CONTROL_TIME_WINDOWS | PECI_PSYS_PL2_POWER_LIMIT_ENABLE |
PECI_PSYS_PL2_POWER_LIMIT(watt);
rv = peci_Wr_Pkg_Config(PECI_INDEX_POWER_LIMITS_PSYS_PL2,
PECI_PARAMS_POWER_LIMITS_PSYS_PL2, data, PECI_WR_PKG_CONFIG_WRITE_LENGTH_DWORD);
if (rv)
return rv;
return EC_SUCCESS;
}
__override int stop_read_peci_temp(void)
{
static uint64_t t;
static int read_count;
uint64_t tnow;
tnow = get_time().val;
if (chipset_in_state(CHIPSET_STATE_ANY_OFF))
return EC_ERROR_NOT_POWERED;
else if (chipset_in_state(CHIPSET_STATE_STANDBY)) {
if (tnow - t < (7 * SECOND))
return EC_ERROR_NOT_POWERED;
else {
/**
* PECI read tempurature three times per second
* dptf.c thermal.c temp_sensor.c
*/
if (++read_count > 3) {
read_count = 0;
t = tnow;
return EC_ERROR_NOT_POWERED;
}
}
} else {
read_count = 0;
t = tnow;
}
return EC_SUCCESS;
}
| C | CL | 2fb2fa509ee860185990fcf1f1b7c58885991f309f01747afa2dbf5623f52713 |
#ifndef PET_SKIP_H
#define PET_SKIP_H
#include <pet.h>
#include "context.h"
#include "state.h"
#if defined(__cplusplus)
extern "C" {
#endif
enum pet_skip_type {
pet_skip_if,
pet_skip_if_else,
pet_skip_seq
};
/* Structure that handles the construction of skip conditions.
*
* scop_then and scop_else represent the then and else branches
* of the if statement
*
* scop1 and scop2 represent the two statements that are combined
*
* skip[type] is true if we need to construct a skip condition of that type
* equal is set if the skip conditions of types pet_skip_now and pet_skip_later
* are equal to each other
* index[type] is an index expression from a zero-dimension domain
* to the virtual array representing the skip condition
* scop[type] is a scop for computing the skip condition
*/
struct pet_skip_info {
isl_ctx *ctx;
enum pet_skip_type type;
int skip[2];
int equal;
isl_multi_pw_aff *index[2];
struct pet_scop *scop[2];
union {
struct {
struct pet_scop *scop_then;
struct pet_scop *scop_else;
} i;
struct {
struct pet_scop *scop1;
struct pet_scop *scop2;
} s;
} u;
};
int pet_skip_info_has_skip(struct pet_skip_info *skip);
void pet_skip_info_if_init(struct pet_skip_info *skip, isl_ctx *ctx,
struct pet_scop *scop_then, struct pet_scop *scop_else,
int have_else, int affine);
void pet_skip_info_if_extract_index(struct pet_skip_info *skip,
__isl_keep isl_multi_pw_aff *index, __isl_keep pet_context *pc,
struct pet_state *state);
void pet_skip_info_if_extract_cond(struct pet_skip_info *skip,
__isl_keep isl_pw_aff *cond, __isl_keep pet_context *pc,
struct pet_state *state);
void pet_skip_info_seq_init(struct pet_skip_info *skip, isl_ctx *ctx,
struct pet_scop *scop1, struct pet_scop *scop2);
void pet_skip_info_seq_extract(struct pet_skip_info *skip,
__isl_keep pet_context *pc, struct pet_state *state);
struct pet_scop *pet_skip_info_add(struct pet_skip_info *skip,
struct pet_scop *scop);
#if defined(__cplusplus)
}
#endif
#endif
| C | CL | 4ce21dcc8289d6c21efb225139fd29f5a5ada993cc8aefb87f6f21be0ca55138 |
/**
* @file src/app/peripheral_mod/vin/sensor/mn34222_a12/sensor_mn34222_a12.c
*
* Implementation of SONY MN34222 related settings.
*
* History:
* 2015/06/02 - [cichen] created file
*
* Copyright (C) 2013, Ambarella, Inc.
*
* All rights reserved. No Part of this file may be reproduced, stored
* in a retrieval system, or transmitted, in any form, or by any means,
* electronic, mechanical, photocopying, recording, or otherwise,
* without the prior consent of Ambarella, Inc.
*/
#include <system/ApplibSys_Sensor.h>
#include <wchar.h>
#include <AmbaSensor.h>
#include <AmbaSensor_MN34222.h>
extern AMBA_SENSOR_OBJ_s AmbaSensor_MN34222Obj;
/** photo quality config table */
#define PHOTO_QUALITY_TABLE_SIZE (4)
static int sensor_mn34222_a12_photo_quality_table[PHOTO_QUALITY_TABLE_SIZE] = {
95, 90, 80, 0xFF
};
/** photo encode window config table */
#define PHOTO_CONFIG_NORMAL_TABLE_SIZE (2)
static int sensor_mn34222_a12_capture_mode_normal_ar_table[PHOTO_CONFIG_NORMAL_TABLE_SIZE] = {
VAR_4x3,
VAR_16x9
};
static UINT32 sensor_mn34222_a12_shutter_mode_normal_table[PHOTO_CONFIG_NORMAL_TABLE_SIZE] = {
SENSOR_DEF_SHUTTER,
SENSOR_DEF_SHUTTER
};
static APPLIB_SENSOR_STILLCAP_CONFIG_s sensor_mn34222_a12_pjpeg_config_normal_table[PHOTO_CONFIG_NORMAL_TABLE_SIZE] = {
{
1,
PHOTO_THUMB_W, PHOTO_THUMB_H_4x3, PHOTO_THUMB_W, PHOTO_THUMB_H_4x3,
PHOTO_SCRN_W, PHOTO_SCRN_H_4x3, PHOTO_SCRN_W, PHOTO_SCRN_H_4x3,
1440, 1080,
PHOTO_QUALITY_DEFAULT, PHOTO_QUALITY_DEFAULT, PHOTO_QUALITY_DEFAULT,
REC_JPEG_DEFAULT},
{
1,
PHOTO_THUMB_W, PHOTO_THUMB_H_4x3, PHOTO_THUMB_W, PHOTO_THUMB_H_16x9,
PHOTO_SCRN_W, PHOTO_SCRN_H_16x9, PHOTO_SCRN_W, PHOTO_SCRN_H_16x9,
1920, 1080,
PHOTO_QUALITY_DEFAULT, PHOTO_QUALITY_DEFAULT, PHOTO_QUALITY_DEFAULT,
REC_JPEG_DEFAULT}
};
static APPLIB_SENSOR_STILLPREV_CONFIG_s sensor_mn34222_a12_pjpeg_config_normal_liveview_table[2][PHOTO_CONFIG_NORMAL_TABLE_SIZE] = {
{{ 1440, 1080, 960, 720, 30000, 1001, VAR_4x3}, {1920, 1080, 960, 540, 30000, 1001, VAR_16x9}},
{{ 1440, 1080, 960, 720, 25000, 1000, VAR_4x3}, {1920, 1080, 960, 540, 25000, 1000, VAR_16x9}}
};
static int sensor_mn34222_a12_pjpeg_mode_id_normal_liveview_table[2][PHOTO_CONFIG_NORMAL_TABLE_SIZE] = {
{MN34222_S1_12_1944X1092_60P_TO_30P, MN34222_S1_12_1944X1092_60P_TO_30P},
{MN34222_S1_12_1944X1092_60P_TO_30P, MN34222_S1_12_1944X1092_60P_TO_30P}
};
static APPLIB_SENSOR_STILLCAP_MODE_CONFIG_s sensor_mn34222_a12_still_capture_mode_table[PHOTO_CONFIG_NORMAL_TABLE_SIZE] = {
{MN34222_S1_12_1944X1092_60P_TO_30P, 1440, 1080},
{MN34222_S1_12_1944X1092_60P_TO_30P, 1920, 1080}
};
#define PHOTO_CONFIG_BURST_TABLE_SIZE (1)
static int sensor_mn34222_a12_capture_mode_burst_ar_table[PHOTO_CONFIG_BURST_TABLE_SIZE] = {
VAR_4x3
};
static UINT32 sensor_mn34222_a12_shutter_mode_burst_table[PHOTO_CONFIG_BURST_TABLE_SIZE] = {
SENSOR_DEF_SHUTTER
};
static APPLIB_SENSOR_STILLCAP_CONFIG_s sensor_mn34222_a12_pjpeg_config_burst_table[PHOTO_CONFIG_BURST_TABLE_SIZE] = {
{
6,
PHOTO_THUMB_W, PHOTO_THUMB_H_4x3, PHOTO_THUMB_W, PHOTO_THUMB_H_4x3,
PHOTO_SCRN_W, PHOTO_SCRN_H_4x3, PHOTO_SCRN_W, PHOTO_SCRN_H_4x3,
1440, 1080,
PHOTO_QUALITY_DEFAULT, PHOTO_QUALITY_DEFAULT, PHOTO_QUALITY_DEFAULT,
REC_JPEG_DEFAULT}
};
static APPLIB_SENSOR_STILLPREV_CONFIG_s sensor_mn34222_a12_pjpeg_config_burst_liveview_table[2][PHOTO_CONFIG_BURST_TABLE_SIZE] = {
{{ 1440, 1080, 960, 720, 30000, 1001, VAR_4x3}},
{{ 1440, 1080, 960, 720, 25000, 1000, VAR_4x3}}
};
static int sensor_mn34222_a12_pjpeg_mode_id_burst_liveview_table[2][PHOTO_CONFIG_BURST_TABLE_SIZE] = {
{MN34222_S1_12_1944X1092_60P_TO_30P},
{MN34222_S1_12_1944X1092_60P_TO_30P}
};
static APPLIB_SENSOR_STILLCAP_MODE_CONFIG_s sensor_mn34222_a12_still_capture_mode_burst_table[PHOTO_CONFIG_BURST_TABLE_SIZE] = {
{MN34222_S1_12_1944X1092_60P_TO_30P, 1440, 1080}
};
/** photo config string table */
static UINT16 sensor_mn34222_a12_normal_photo_size_string_table[PHOTO_CONFIG_NORMAL_TABLE_SIZE][SENSOR_PHOTO_SIZE_STR_LEN] = {
{'2','M',' ','(','1','4','4','0','x','1','0','8','0',' ','4',':','3',')','\0'},
{'2','M',' ','(','1','9','2','0','x','1','0','8','0',' ','1','6',':','9',')','\0'}
};
static UINT16 sensor_mn34222_a12_burst_photo_size_string_table[PHOTO_CONFIG_BURST_TABLE_SIZE][SENSOR_PHOTO_SIZE_STR_LEN] = {
{'2','M',' ','(','1','4','4','0','x','1','0','8','0',' ','4',':','3',')','\0'}
};
#define VIDEO_RES_TABLE_SIZE (3)
static int sensor_mn34222_a12_video_res_table[VIDEO_RES_TABLE_SIZE] = {
SENSOR_VIDEO_RES_TRUE_1080P_FULL,
SENSOR_VIDEO_RES_TRUE_1080P_HALF,
SENSOR_VIDEO_RES_TRUE_1080P_HALF_HDR
};
static int sensor_video_res_table_size = VIDEO_RES_TABLE_SIZE;
static int *sensor_video_res_table = sensor_mn34222_a12_video_res_table;
/**
* @brief Initialize the information of sensor
*
* Initialize the information of sensor
*
* @param [in] channel channel
*
* @return >=0 success, <0 failure
*/
static int sensor_mn34222_a12_init(AMBA_DSP_CHANNEL_ID_u channel)
{
int ReturnValue = 0;
return ReturnValue;
}
/**
* @brief Get the strings of photo size
*
* Get the strings of photo size
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static UINT16* sensor_mn34222_a12_get_photo_size_str(int capMode, int pjpegConfigID)
{ switch (capMode) {
case SENSOR_PHOTO_CAP_NORMAL:
if (pjpegConfigID >= PHOTO_CONFIG_NORMAL_TABLE_SIZE) {
return sensor_mn34222_a12_normal_photo_size_string_table[0];
} else {
return sensor_mn34222_a12_normal_photo_size_string_table[pjpegConfigID];
}
break;
case SENSOR_PHOTO_CAP_BURST:
if (pjpegConfigID >= PHOTO_CONFIG_BURST_TABLE_SIZE) {
return sensor_mn34222_a12_burst_photo_size_string_table[0];
} else {
return sensor_mn34222_a12_burst_photo_size_string_table[pjpegConfigID];
}
break;
default:
AmbaPrintColor(RED,"Sensor mn34222pa doesn't support this capture mode. Cap mode is %d", capMode);
return NULL;
break;
}
}
/**
* @brief Get sensor mode of photo liveview mode.
*
* Get sensor mode of photo liveview mode.
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static int sensor_mn34222_a12_get_photo_liveview_mode_id(int capMode, int pjpegConfigID)
{
int ReturnValue = 0;
int VinSystem = AppLibSysVin_GetSystemType();
switch (capMode) {
case SENSOR_PHOTO_CAP_NORMAL:
if (pjpegConfigID >= PHOTO_CONFIG_NORMAL_TABLE_SIZE) {
ReturnValue = sensor_mn34222_a12_pjpeg_mode_id_normal_liveview_table[VinSystem][0];
} else {
ReturnValue = sensor_mn34222_a12_pjpeg_mode_id_normal_liveview_table[VinSystem][pjpegConfigID];
}
break;
case SENSOR_PHOTO_CAP_BURST:
if (pjpegConfigID >= PHOTO_CONFIG_BURST_TABLE_SIZE) {
ReturnValue = sensor_mn34222_a12_pjpeg_mode_id_burst_liveview_table[VinSystem][0];
} else {
ReturnValue = sensor_mn34222_a12_pjpeg_mode_id_burst_liveview_table[VinSystem][pjpegConfigID];
}
break;
default:
ReturnValue = -1;
AmbaPrintColor(RED,"Sensor mn34222 doesn't support this capture mode. Cap mode is %d", capMode);
break;
}
return ReturnValue;
}
/**
* @brief Get sensor mode of photo High frame mode.
*
* Get sensor mode of photo High frame mode.
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static int sensor_mn34222_a12_get_photo_hfr_mode_id(int capMode, int pjpegConfigID)
{
int ReturnValue = -1;
return ReturnValue;
}
/**
* @brief Get sensor mode of photo High frame preflash mode.
*
* Get sensor mode of photo High frame mode.
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static int sensor_mn34222_a12_get_photo_preflash_hfr_mode_id(int capMode, int pjpegConfigID)
{
int ReturnValue = -1;
return ReturnValue;
}
/**
* @brief Get sensor mode of photo normal capture mode.
*
* Get sensor mode of photo normal capture mode.
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static APPLIB_SENSOR_STILLCAP_MODE_CONFIG_s* sensor_mn34222_a12_get_still_capture_mode_config(int capMode, int pjpegConfigID)
{
APPLIB_SENSOR_STILLCAP_MODE_CONFIG_s *ReturnValue = NULL;
switch (capMode) {
case SENSOR_PHOTO_CAP_NORMAL:
if (pjpegConfigID >= PHOTO_CONFIG_NORMAL_TABLE_SIZE) {
ReturnValue = &sensor_mn34222_a12_still_capture_mode_table[0];
} else {
ReturnValue = &sensor_mn34222_a12_still_capture_mode_table[pjpegConfigID];
}
break;
case SENSOR_PHOTO_CAP_BURST:
if (pjpegConfigID >= PHOTO_CONFIG_BURST_TABLE_SIZE) {
ReturnValue = &sensor_mn34222_a12_still_capture_mode_burst_table[0];
} else {
ReturnValue = &sensor_mn34222_a12_still_capture_mode_burst_table[pjpegConfigID];
}
break;
default:
ReturnValue = NULL;
AmbaPrintColor(RED,"Sensor mn34222 doesn't support this capture mode. Cap mode is %d, pjpegConfigID is %d", capMode, pjpegConfigID);
K_ASSERT(0);
break;
}
return ReturnValue;
}
/**
* @brief Get sensor mode of photo OB mode.
*
* Get sensor mode of photo normal capture mode.
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static int sensor_mn34222_a12_get_still_capture_ob_mode_id(int capMode, int pjpegConfigID)
{
int ReturnValue = -1;
return ReturnValue;
}
/**
* @brief Get aspect ratio of photo mode.
*
* Get aspect ratio of photo mode.
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static int sensor_mn34222_a12_get_capture_mode_ar(int capMode, int pjpegConfigID)
{
int ReturnValue = -1;
switch (capMode) {
case SENSOR_PHOTO_CAP_NORMAL:
if (pjpegConfigID >= PHOTO_CONFIG_NORMAL_TABLE_SIZE) {
ReturnValue = sensor_mn34222_a12_capture_mode_normal_ar_table[0];
} else {
ReturnValue = sensor_mn34222_a12_capture_mode_normal_ar_table[pjpegConfigID];
}
break;
case SENSOR_PHOTO_CAP_BURST:
if (pjpegConfigID >= PHOTO_CONFIG_BURST_TABLE_SIZE) {
ReturnValue = sensor_mn34222_a12_capture_mode_burst_ar_table[0];
} else {
ReturnValue = sensor_mn34222_a12_capture_mode_burst_ar_table[pjpegConfigID];
}
break;
default:
ReturnValue = -1;
AmbaPrintColor(RED,"Sensor mn34222 doesn't support this capture mode. Cap mode is %d", capMode);
break;
}
return ReturnValue;
}
/**
* @brief Get the preview window size
*
* Get the preview window size
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
* @param [in] video_plane_dev video plane of device
* @param [out] width Width
* @param [out] height Height
*
* @return >=0 success, <0 failure
*/
static int sensor_mn34222_a12_get_preview_window(int capMode, int pjpegConfigID, int *width, int *height)
{
int ReturnValue = 0;
return ReturnValue;
}
/**
* @brief Get the quality setting of photo mode.
*
* Get the quality setting of photo mode.
*
* @param [in] qualityMode The quality mode
*
* @return Quality setting
*/
static int sensor_mn34222_a12_get_photo_quality_config(int qualityMode)
{
return sensor_mn34222_a12_photo_quality_table[qualityMode];
}
/**
* @brief Get the photo liveview config.
*
* Get the photo liveview config.
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static APPLIB_SENSOR_STILLPREV_CONFIG_s* sensor_mn34222_a12_get_photo_liveview_config(int capMode, int pjpegConfigID)
{
APPLIB_SENSOR_STILLPREV_CONFIG_s *ReturnValue = NULL;
int VinSystem = AppLibSysVin_GetSystemType();
switch (capMode) {
case SENSOR_PHOTO_CAP_NORMAL:
if (pjpegConfigID >= PHOTO_CONFIG_NORMAL_TABLE_SIZE) {
ReturnValue = &sensor_mn34222_a12_pjpeg_config_normal_liveview_table[VinSystem][0];
} else {
ReturnValue = &sensor_mn34222_a12_pjpeg_config_normal_liveview_table[VinSystem][pjpegConfigID];
}
break;
case SENSOR_PHOTO_CAP_BURST:
if (pjpegConfigID >= PHOTO_CONFIG_BURST_TABLE_SIZE) {
ReturnValue = &sensor_mn34222_a12_pjpeg_config_burst_liveview_table[VinSystem][0];
} else {
ReturnValue = &sensor_mn34222_a12_pjpeg_config_burst_liveview_table[VinSystem][pjpegConfigID];
}
break;
default:
ReturnValue = NULL;
AmbaPrintColor(RED,"Sensor mn34222 doesn't support this capture mode. Cap mode is %d", capMode);
break;
}
return ReturnValue;
}
/**
* @brief Get the photo jpge config
*
* Get the photo jpge config
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static APPLIB_SENSOR_STILLCAP_CONFIG_s* sensor_mn34222_a12_get_pjpeg_config(int capMode, int pjpegConfigID)
{
APPLIB_SENSOR_STILLCAP_CONFIG_s *ReturnValue = NULL;
switch (capMode) {
case SENSOR_PHOTO_CAP_NORMAL:
if (pjpegConfigID >= PHOTO_CONFIG_NORMAL_TABLE_SIZE) {
ReturnValue = &sensor_mn34222_a12_pjpeg_config_normal_table[0];
} else {
ReturnValue = &sensor_mn34222_a12_pjpeg_config_normal_table[pjpegConfigID];
}
break;
case SENSOR_PHOTO_CAP_BURST:
if (pjpegConfigID >= PHOTO_CONFIG_BURST_TABLE_SIZE) {
ReturnValue = &sensor_mn34222_a12_pjpeg_config_burst_table[0];
} else {
ReturnValue = &sensor_mn34222_a12_pjpeg_config_burst_table[pjpegConfigID];
}
break;
default:
ReturnValue = NULL;
AmbaPrintColor(RED,"Sensor mn34222 doesn't support this capture mode. Cap mode is %d", capMode);
break;
}
return ReturnValue;
}
/**
* @brief Get the shutter mode under photo capture mode
*
* Get the shutter mode under photo capture mode
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static UINT32 sensor_mn34222_a12_get_shutter_mode(int capMode, int pjpegConfigID)
{
UINT32 ReturnValue = 0;
switch (capMode) {
case SENSOR_PHOTO_CAP_NORMAL:
if (pjpegConfigID >= PHOTO_CONFIG_NORMAL_TABLE_SIZE) {
ReturnValue = sensor_mn34222_a12_shutter_mode_normal_table[0];
} else {
ReturnValue = sensor_mn34222_a12_shutter_mode_normal_table[pjpegConfigID];
}
break;
case SENSOR_PHOTO_CAP_BURST:
if (pjpegConfigID >= PHOTO_CONFIG_BURST_TABLE_SIZE) {
ReturnValue = sensor_mn34222_a12_shutter_mode_burst_table[0];
} else {
ReturnValue = sensor_mn34222_a12_shutter_mode_burst_table[pjpegConfigID];
}
break;
default:
ReturnValue = -1;
AmbaPrintColor(RED,"Sensor mn34222 doesn't support this capture mode. Cap mode is %d", capMode);
break;
}
return ReturnValue;
}
/**
* @brief Get maximum shutter time
*
* Get maximum shutter time
*
* @param [in] capMode Capture mode
* @param [in] pjpegConfigID Photo config id
*
* @return >=0 success, <0 failure
*/
static int sensor_mn34222_a12_get_max_shutter_time(int capMode, int pjpegConfigID)
{
int ReturnValue = 0;
return ReturnValue;
}
/**
* @brief Get the resolution id of video record mode that this sensor support
*
* Get the resolution id of video record mode that this sensor support
*
* @param [in] resRef The index that this sensor support
*
* @return >=0 Resolution id, <0 failure
*/
static int sensor_mn34222_a12_get_videoResID(int resRef)
{
if ((resRef >= 0) || (resRef < sensor_video_res_table_size)) {
return sensor_video_res_table[resRef];
} else {
AmbaPrint("[App] Sensor mn34222 Invalid resolution reference");
return -1;
}
}
/**
* @brief Get the strings of video recording mode.
*
* Get the strings of video recording mode.
*
* @param [in] videoResID Resolution id
*
* @return strings index
*/
static UINT16* sensor_mn34222_a12_get_video_res_str(int videoResID)
{
if (AppLibSysVin_GetSystemType() == VIN_SYS_PAL) {
extern UINT16 sensor_video_res_string_table_pal[][SENSOR_VIDEO_RES_STR_LEN];
return sensor_video_res_string_table_pal[videoResID];
} else {
extern UINT16 sensor_video_res_string_table_ntsc[][SENSOR_VIDEO_RES_STR_LEN];
return sensor_video_res_string_table_ntsc[videoResID];
}
}
/**
* @brief Get sensor mode of video recording mode
*
* Get sensor mode of video recording mode
*
* @param [in] vin_config Vin config
*
* @return >=0 VinMode, <0 failure
*/
static int sensor_mn34222_a12_get_vinMode(APPLIB_SENSOR_VIN_CONFIG_s *vin_config)
{
int ReturnValue = -1;
int VinSystem = AppLibSysVin_GetSystemType();
switch (vin_config->ResID) {
case SENSOR_VIDEO_RES_TRUE_1080P_HALF:
case SENSOR_VIDEO_RES_HD_HALF:
if (VinSystem == VIN_SYS_PAL) {
ReturnValue = MN34222_S1_12_1944X1092_60P_TO_30P;
} else {
ReturnValue = MN34222_S1_12_1944X1092_60P_TO_30P;
}
break;
case SENSOR_VIDEO_RES_TRUE_1080P_FULL:
case SENSOR_VIDEO_RES_HD_FULL:
if (VinSystem == VIN_SYS_PAL) {
ReturnValue = MN34222_S1_12_1944X1092_60P;
} else {
ReturnValue = MN34222_S1_12_1944X1092_60P;
}
break;
case SENSOR_VIDEO_RES_TRUE_1080P_HALF_HDR:
if (VinSystem == VIN_SYS_PAL) {
ReturnValue = MN34222_S1_12_1944X1092_30P_HDR;
} else {
ReturnValue = MN34222_S1_12_1944X1092_30P_HDR;
}
break;
default:
AmbaPrintColor(RED,"[App] Sensor mn34222 doesn't support this resolution %d ", vin_config->ResID);
K_ASSERT(0);
break;
}
AmbaPrintColor(BLUE, "Vin Mode = %d", ReturnValue);
return ReturnValue;
}
/**
* @brief Get video config
*
* Get video config
*
* @param [in] videoResID Video resolution id
*
* @return >=0 The address of config file, <0 failure
*/
static APPLIB_SENSOR_VIDEO_ENC_CONFIG_s* sensor_mn34222_a12_get_video_config(int videoResID)
{
if (AppLibSysVin_GetSystemType() == VIN_SYS_PAL) {
extern APPLIB_SENSOR_VIDEO_ENC_CONFIG_s SensorVideoEncConfigTablePAL[];
switch (videoResID) {
case SENSOR_VIDEO_RES_TRUE_1080P_FULL:
case SENSOR_VIDEO_RES_TRUE_1080P_HALF:
SensorVideoEncConfigTablePAL[videoResID].CaptureWidth = 1920;
SensorVideoEncConfigTablePAL[videoResID].CaptureHeight = 1080;
break;
case SENSOR_VIDEO_RES_TRUE_1080P_HALF_HDR:
SensorVideoEncConfigTablePAL[videoResID].CaptureWidth = 1956;
SensorVideoEncConfigTablePAL[videoResID].CaptureHeight = 2996;
break;
default:
break;
}
return &SensorVideoEncConfigTablePAL[videoResID];
} else {
extern APPLIB_SENSOR_VIDEO_ENC_CONFIG_s SensorVideoEncConfigTableNTSC[];
switch (videoResID) {
case SENSOR_VIDEO_RES_TRUE_1080P_FULL:
case SENSOR_VIDEO_RES_TRUE_1080P_HALF:
SensorVideoEncConfigTableNTSC[videoResID].CaptureWidth = 1920;
SensorVideoEncConfigTableNTSC[videoResID].CaptureHeight = 1080;
break;
case SENSOR_VIDEO_RES_TRUE_1080P_HALF_HDR:
SensorVideoEncConfigTableNTSC[videoResID].CaptureWidth = 1956;
SensorVideoEncConfigTableNTSC[videoResID].CaptureHeight = 2996;
break;
default:
break;
}
return &SensorVideoEncConfigTableNTSC[videoResID];
}
}
/**
* @brief Get the bit rate control table under video recording mode
*
* Get the bit rate control table under video recording mode
*
* @param [in] videoResID Video resolution id
* @param [in] videoQuality
*
* @return >=0 bit rate table, <0 failure
*/
static APPLIB_VIDEOENC_BITRATE_s* sensor_mn34222_a12_get_video_brc(int videoResID, int videoQuality)
{
extern APPLIB_VIDEOENC_BITRATE_s SensorVideoBitRateTable[][VIDEO_QUALITY_NUM];
return &SensorVideoBitRateTable[videoResID][videoQuality];
}
/**
* @brief Get the GOP table under video recording mode
*
* Get the GOP table under video recording mode
*
* @param [in] videoResID Video resolution id
*
* @return >=0 Gop Table, <0 failure
*/
static APPLIB_VIDEOENC_GOP_s* sensor_mn34222_a12_get_video_gop(int videoResID)
{
extern APPLIB_VIDEOENC_GOP_s SensorVideoGOPTable[];
return &SensorVideoGOPTable[videoResID];
}
/**
* @brief Check the video resolution valid in this sensor setting.
*
* Check the video resolution valid in this sensor setting.
*
* @param [in] videoResID Video resolution id
*
* @return >=0 success, <0 failure
*/
static int sensor_mn34222_a12_check_video_res(int videoResID)
{
int i = 0;
for (i=0; i<sensor_video_res_table_size; i++) {
if (videoResID == sensor_video_res_table[i]) {
return sensor_video_res_table[i];
}
}
AmbaPrint("Not supported video resolution. Return default video resolution");
return sensor_video_res_table[0];
}
/**
* @brief Get the PIV config table
*
* Get the PIV config table
*
* @param [in] videoResID Video resolution id
*
* @return PIV config table
*/
static APPLIB_SENSOR_PIV_CONFIG_s* sensor_mn34222_a12_get_piv_config(int videoResID)
{
extern APPLIB_SENSOR_PIV_CONFIG_s SensorPIVConfigTable[];
return &SensorPIVConfigTable[videoResID];
}
/**
* @brief Get PIV Size config
*
* Get PIV Size config
*
* @param [in] videoResID Video resolution id
* @param [out] PIVCapConfig PIV capture size config
*
* @return 0 success <0 failure
*/
static int sensor_mn34222_a12_get_piv_size(int videoResID, APPLIB_SENSOR_PIV_ENC_CONFIG_s *PIVCapConfig)
{
int ReturnValue = 0;
extern APPLIB_SENSOR_VIDEO_ENC_CONFIG_s SensorVideoEncConfigTableNTSC[];
if (SensorVideoEncConfigTableNTSC[videoResID].VAR == VAR_16x9) {
PIVCapConfig->VAR = VAR_16x9;
PIVCapConfig->ScreennailWidth = PHOTO_SCRN_W;
PIVCapConfig->ScreennailHeight = PHOTO_SCRN_H_16x9;
PIVCapConfig->ScreennailActiveWidth = PHOTO_SCRN_W;
PIVCapConfig->ScreennailActiveHeight = PHOTO_SCRN_H_16x9;
PIVCapConfig->ThumbnailWidth = PHOTO_THUMB_W;
PIVCapConfig->ThumbnailHeight = PHOTO_THUMB_H_4x3;
PIVCapConfig->ThumbnailActiveWidth = PHOTO_THUMB_W;
PIVCapConfig->ThumbnailActiveHeight = PHOTO_THUMB_H_16x9;
PIVCapConfig->ThumbnailQality = PHOTO_QUALITY_DEFAULT;
PIVCapConfig->FullviewQuality = PHOTO_QUALITY_DEFAULT;
PIVCapConfig->ScreennailQuality = PHOTO_QUALITY_DEFAULT;
} else if (SensorVideoEncConfigTableNTSC[videoResID].VAR == VAR_4x3) {
PIVCapConfig->VAR = VAR_4x3;
PIVCapConfig->ScreennailWidth = PHOTO_SCRN_W;
PIVCapConfig->ScreennailHeight = PHOTO_SCRN_H_4x3;
PIVCapConfig->ScreennailActiveWidth = PHOTO_SCRN_W;
PIVCapConfig->ScreennailActiveHeight = PHOTO_SCRN_H_4x3;
PIVCapConfig->ThumbnailWidth = PHOTO_THUMB_W;
PIVCapConfig->ThumbnailHeight = PHOTO_THUMB_H_4x3;
PIVCapConfig->ThumbnailActiveWidth = PHOTO_THUMB_W;
PIVCapConfig->ThumbnailActiveHeight = PHOTO_THUMB_H_4x3;
PIVCapConfig->ThumbnailQality = PHOTO_QUALITY_DEFAULT;
PIVCapConfig->FullviewQuality = PHOTO_QUALITY_DEFAULT;
PIVCapConfig->ScreennailQuality = PHOTO_QUALITY_DEFAULT;
}
switch (videoResID) {
case SENSOR_VIDEO_RES_TRUE_1080P_FULL:
case SENSOR_VIDEO_RES_TRUE_1080P_HALF:
case SENSOR_VIDEO_RES_TRUE_1080P_HALF_HDR:
PIVCapConfig->CaptureWidth = 1920;
PIVCapConfig->CaptureHeight = 1080;
break;
default:
break;
}
return ReturnValue;
}
/**
* @brief Register the sensor's information.
*
* Register the sensor's information.
*
* @return >=0 success, <0 failure
*/
int AppSensor_register_mn34222_a12(void)
{
APPLIB_SENSOR_s Dev = {0};
char DevName[] = {'m','n','3','4','2','2','2','_','a','1','2','\0'};
Dev.ID = 0;
strcpy(Dev.Name, DevName);
Dev.SysCapacity = SENSOR_SYS_NTSC | SENSOR_SYS_PAL;
Dev.DzoomCapacity = 0;
Dev.Rotate = SENSOR_ROTATE_0;
Dev.VideoResNum = sensor_video_res_table_size;
Dev.PjpegConfigNormalNum = PHOTO_CONFIG_NORMAL_TABLE_SIZE;
Dev.PjpegConfigCollageNum = 0;
Dev.PjpegConfigBurstNum = PHOTO_CONFIG_BURST_TABLE_SIZE;
Dev.PhotoMaxVcapWidth = 4608;
Dev.PhotoMaxVcapHeight = 3456;
Dev.PhotoMaxEncWeight = 4608;
Dev.PhotoMaxEncHeight = 3456;
Dev.PhotoMaxPrevWidth = 2312;
Dev.PhotoMaxPrevHeight = 1734;
Dev.Init = sensor_mn34222_a12_init;
Dev.GetVideoResID = sensor_mn34222_a12_get_videoResID;
Dev.GetPhotoLiveviewModeID = sensor_mn34222_a12_get_photo_liveview_mode_id;
Dev.GetPhotoHfrModeID = sensor_mn34222_a12_get_photo_hfr_mode_id;
Dev.GetPhotoPreflashHfrModeID = sensor_mn34222_a12_get_photo_preflash_hfr_mode_id;
Dev.GetStillCaptureModeConfig =sensor_mn34222_a12_get_still_capture_mode_config;
Dev.GetStillCaptureObModeID =sensor_mn34222_a12_get_still_capture_ob_mode_id;
Dev.GetVideoResString = sensor_mn34222_a12_get_video_res_str;
Dev.GetPhotoSizeString = sensor_mn34222_a12_get_photo_size_str;
Dev.GetVinMode = sensor_mn34222_a12_get_vinMode;
Dev.GetCaptureModeAR = sensor_mn34222_a12_get_capture_mode_ar;
Dev.GetPreviewWindow = sensor_mn34222_a12_get_preview_window;
Dev.GetPhotoQualityConfig = sensor_mn34222_a12_get_photo_quality_config;
Dev.GetPhotoLiveviewConfig = sensor_mn34222_a12_get_photo_liveview_config;
Dev.GetPjpegConfig = sensor_mn34222_a12_get_pjpeg_config;
Dev.GetVideoConfig = sensor_mn34222_a12_get_video_config;
Dev.GetVideoBiteRate = sensor_mn34222_a12_get_video_brc;
Dev.GetVideoGOP = sensor_mn34222_a12_get_video_gop;
Dev.CheckVideoRes = sensor_mn34222_a12_check_video_res;
Dev.GetPIVConfig = sensor_mn34222_a12_get_piv_config;
Dev.GetPIVSize = sensor_mn34222_a12_get_piv_size;
Dev.GetShutterMode = sensor_mn34222_a12_get_shutter_mode;
Dev.GetMaxShutterTime = sensor_mn34222_a12_get_max_shutter_time;
AppLibSysSensor_Attach(&Dev);
return 0;
}
| C | CL | b29b1801d6798d9e269337e2131f8b4a72307257add80351aef623c2f3459522 |
/*
* lcd_driver.h
*
* Created on: Apr 25, 2019
* Author: deepe
*
* https://mil.ufl.edu/3744/docs/lcdmanual/commands.html
*/
#ifndef INC_LCD_DRIVER_H_
#define INC_LCD_DRIVER_H_
#include "stdint.h"
#include "tasks_driver.h"
#include "driverlib/gpio.h"
#include "inc/hw_memmap.h"
#include "driverlib/pin_map.h"
/*LCD Commands*/
#define CLEAR_DISPLAY (0x01)
#define CURSOR_HOME (0x02)
#define ENTRY_MODE (0x06)
#define DISPLAY_ON (0x0C)
#define CURSOR_ON (0x0A)
#define CURSOR_BLINK (0x0F)
#define DISPLAY_OFF (0x08)
#define DISPLAY_SHIFT (0x10)
#define SYSTEM_SET (0x38)
#define FIRST_LINE (0x80)
#define SECOND_LINE (0xC0)
#define THIRD_LINE (0x90)
#define FOURTH_LINE (0xD0)
#define BIT_MODE_8 (0x30)
#define BIT_MODE_4 (0x30)
// Microsecond Count for delay
#define MICROSECOND (160000)
#define RS_1 GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_4, GPIO_PIN_4);
#define RS_0 GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_4, 0);
//#define RW_1 GPIOPinWrite(GPIO_PORTP_BASE, GPIO_PIN_1, GPIO_PIN_1);
//#define RW_0 GPIOPinWrite(GPIO_PORTP_BASE, GPIO_PIN_1, 0);
#define Enable_1 GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_5, GPIO_PIN_5);
#define Enable_0 GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_5, 0);
#define Write(data) GPIOPinWrite(GPIO_PORTK_BASE, /*GPIO_PIN_7 | GPIO_PIN_6 | GPIO_PIN_5 | GPIO_PIN_4 */ GPIO_PIN_3 | GPIO_PIN_2 | GPIO_PIN_1 | GPIO_PIN_0 ,data);
/**
* @brief Initialize LCD gpio pins
* @return void
*/
void InitializeLCD();
/**
* @brief
* @param character
* @return void
*/
void LCDWriteChar(char character);
/**
* @brief Write command to LCD
* @param command
*/
void LCDWriteCommand(uint8_t command);
/**
* @brief Write string to LCD
* @param data
* @param line
*/
void LCDWriteStr(char* data,int line);
/**
* @brief Turn on Display
* @return void
*/
void TurnOnLCD();
/**
* @brief Clear LCd dislay
* @return void
*/
void LCDClearDisplay();
#endif /* INC_LCD_DRIVER_H_ */
| C | CL | f7e6939b6acdb9c95a279ca882696ea60a060b01332bb99b4f0baffc3968ba90 |
#ifndef _GAMEDB_H
#define _GAMEDB_H
#include "core/db/asyndb.h"
#include "../avatar.h"
int32_t init_gamedb_module();
int32_t gamedb_request(player_t,db_request_t request);
#endif
| C | CL | 6d92ef0a272243a814eb5f089dd871ff85fb166f8348aba37fecd33e6b7e36f7 |
/*
* Predmet: Formalne jazyky a prekladace (IFJ) - FIT VUT v Brne
* Hlavickovy subor error kniznice pre projekt IFJ2020
* Vytvoril: Martin Novotny - xnovot1r
*
* Datum: 10/2020
*/
#ifndef IFJ2020_ERROR_H
#define IFJ2020_ERROR_H
#include "tokenList.h"
#define ERR_LEX 1
#define ERR_SYN 2
#define ERR_SEM_UNDEF 3
#define ERR_SEM_DATATYPE 4
#define ERR_SEM_EXCOMPAT 5
#define ERR_SEM_RETURN 6
#define ERR_SEM_OTHER 7
#define ERR_SEM_ZERODIV 9
#define ERR_INTERN 99
void error_call(int err, TDLList *L);
#endif //IFJ2020_ERROR_H
| C | CL | 018f684ebc5314aa4f89f9ccc07dd0ebdbf473bc5a9bbdaa6e3f3bcaf1292d5b |
//说明:FSK载波 过零发送模式
//从 plcfsk_rx_v12z_hd.c 修改而来
#include <hic.h>
#include "type.h"
#include "system.h"
#include "timer8n.h"
#include "soc_25xx.h"
#include "tool.h"
#include "debug.h"
#include "config.h"
#ifdef CONFIG_400BPS_PLC
#define CCPMODE 0x02
#define COMPMODE 0x01
#define RH_Time 0X05
#define RL_Time 0X33
#ifdef SENDER
#define R_LED PB5
#else
#define R_LED PB7
#endif
#define S_LED PB7
#define STA PB6
#define PLC_TXEN PC1
#define PLC_TX PLC_TXEN=1
#define PLC_RX PLC_TXEN=0
#define Sync_bit1_cnt_Max 0x1f
#define TX_Bit1() PLC_MOD|=0x01 //PLC_TXD
#define TX_Bit0() PLC_MOD&=0xfe
#define MaxPlcL 100
#define Zero_Num 4
#define NORMAL 0x03
#define PnNum_Const 15
#define Sync_Set 0x5A
#define Sync21_Set 0x6e
#define Sync_Char 0xaf
#define Pn7_Con1 0X17
#define RECV_BITS 23
static volatile section64 sbit PLC_FSK_RXD @ (unsigned) &PLC_MOD* 8 + 3 ;
unsigned char Sync_bit1_cnt,Work_step;
uchar section1 testbyte, Rx_status;
/* 8ms*/ /* 6.7ms*/
const uchar T16g1RH_Time[6]={0x40,0x9c,0xdc,0x82,0xad,0x6e};
uchar Sum_Max,ZXDM,Sum_FXMax,Temp1,FXDM;
section20 uchar BitData_T[64]@0xa00;//BitDataBak_T[16]; //同步时的位数据
section20 uchar Bit1Num_T[64]@0xa40;
section21 uchar BitData_T1[64]@0xa80;//BitDataBak_T[16]; //同步时的位数据
section21 uchar Bit1Num_T1[64]@0xac0;
uchar SYM_offset,SYCl_offset;
uchar SYM_offset2,SYCl_offset2;
uchar SYM_offset3,SYCl_offset3;
uchar SYM_offset4,SYCl_offset4;
uchar Sync_Step;
uchar plc_byte_data,sync_word_l;
sbit r_sync_bit,t_nor_bit,t_end_bit,Plc_SyncBZ,Psk_FxBz,Rec_Zero_bz;
sbit Plc_Tx_Bit,Plc_Tx_first_Bit,Plc_Tx_Second_Bit, Plc_Tx_Third_Bit, Plc_Tx_Forth_Bit;
uchar Plc_data_bit_cnt,Plc_data_byte_cnt,Plc_data_len,Plc_Mode,Plc_ZeroMode;
uchar Plc_Samples_bit1_cnt, Plc_Samples_byte;
section3 uchar plc_data[MaxPlcL]@0x180;
section3 uchar RSSIV,RSSIT;
section3 uchar SYM_off[8],SYCl_off[8];
section14 uchar Zero_cnt;
section14 union SVR_INT_B08 T16G1R_int[8],T16G1R_20ms[8],T16G1R_old,T16G1R_new;//T16G1R1,T16G1R2,T16G1R3,T16G1R4,T16G1R5,T16G1R6;
section14 union SVR_LONG_B08 T16G1R_S;
section13 uchar RSSIByte_buf[32],RSSIBit_buf[8];
section13 uchar ZXDM_buf[40],RSSIV_buf[40];
#define trans_step_next()\
do {\
T16G2RH=T16G1R_S.NumChar[1]; \
T16G2RL=T16G1R_S.NumChar[0]; \
}while(0);
#define plc_restart() \
do{\
T16G2IE=0;\
Plc_Mode=0;\
Work_step=0;\
Sync_Step=0;\
Plc_SyncBZ=0;\
r_sync_bit = 0;\
T16G1IF=0;\
T16G1IE=1;\
}while(0);
#define plc_recv_finished()\
do{\
disable_irq();\
T16G2IE=0;\
T16G1IE=0;\
}while(0);\
#define do_left_shift_1bit(b) \
do {\
BitData_T[b]<<=1;\
if(BitData_T[b+1]&0x80) \
{ \
BitData_T[b]++; \
Bit1Num_T[b]++;\
Bit1Num_T[b+1]--;\
}\
}while(0);
#define do_left_shift_1bit_1(b) \
do {\
BitData_T1[b]<<=1;\
if(BitData_T1[b+1]&0x80) \
{ \
BitData_T1[b]++; \
Bit1Num_T1[b]++;\
Bit1Num_T1[b+1]--;\
}\
}while(0);
void IniT16G1(uchar Mode)
{
if(Mode==CCPMODE) //捕获
{
T16G1CL=0x21;
T16G1CH=0x04;
}
else if(Mode==COMPMODE) //比较
{
T16G1CH=0x0b;
T16G1RH=RH_Time;
T16G1RL=RL_Time;
T16G1CL=0x21; //4:1
}
}
void IniT16G2(uchar Mode)
{
T16G2CH=0x0b;
T16G2CL=0x10; //2:1
switch(Mode)
{
case 1:
// T16G1RH=T16G1R_S.NumChar[1]; //赋下次过零接收时间
// T16G1RL=T16G1R_S.NumChar[0];
T16G2RH=T16g1RH_Time[1]; //过零后8ms发
T16G2RL=T16g1RH_Time[0];
break;
case 2:
// T16G1RH=T16G1R_S.NumChar[1]; //赋下次过零接收时间
// T16G1RL=T16G1R_S.NumChar[0];
T16G2RH=T16g1RH_Time[3]; //过零后6.7ms发
T16G2RL=T16g1RH_Time[2];
break;
case 3:
// T16G1RH=T16G1R_S.NumChar[1]; //赋下次过零接收时间
// T16G1RL=T16G1R_S.NumChar[0];
T16G2RH=T16g1RH_Time[5]; //过零后ms发
T16G2RL=T16g1RH_Time[4];
break;
default:
T16G2RH=T16G1R_S.NumChar[1]; //赋下次过零接收时间
T16G2RL=T16G1R_S.NumChar[0];
break;
}
T16G2L=10;
T16G2H=0;
T16G2CL=0x11; //4:1
}
void Ini_Plc_Rec(void)
{
PLC_RW=0x02;
PLC_ADDR=PLC_00H_LNA1T0;
PLC_DATA=0X43; //0x44
PLC_ADDR=PLC_01H_LNA1T1;
PLC_DATA=0X44;
PLC_ADDR=PLC_02H_LNA1T2;
PLC_DATA=0X41;
PLC_ADDR=PLC_03H_LNA2T0;
PLC_DATA=0X38; //0x88
PLC_ADDR=PLC_04H_LNA2T1;
PLC_DATA=0X88;
PLC_ADDR=PLC_05H_LNA2T2;
PLC_DATA=0X04;
PLC_ADDR=PLC_06H_LPFT;
PLC_DATA=0XB1;
PLC_ADDR=PLC_07H_PGA1T0;
PLC_DATA=0X45; //0x40
PLC_ADDR=PLC_08H_PGA1T1;
PLC_DATA=0X18;
PLC_ADDR=PLC_09H_PGA1T2;
PLC_DATA=0X88;
PLC_ADDR=PLC_0AH_PGA2T0;
PLC_DATA=0X1F; //0x3f
PLC_ADDR=PLC_0BH_PGA2T1;
PLC_DATA=0X88;
PLC_ADDR=PLC_0CH_PGA2T2;
PLC_DATA=0X01;
PLC_ADDR=PLC_0DH_ADCT0;
PLC_DATA=0X80;
PLC_ADDR=PLC_0EH_ADCT1;
PLC_DATA=0X88;
PLC_ADDR=PLC_0FH_ADCT2;
PLC_DATA=0X88;
PLC_ADDR=PLC_10H_ADCT3;
PLC_DATA=0X88;
PLC_ADDR=PLC_11H_DACT0;
PLC_DATA=0X13;
PLC_ADDR=PLC_12H_PAMPT0;
PLC_DATA=0X03;
PLC_ADDR=PLC_13H_PDT0;
PLC_DATA=0;
PLC_ADDR=PLC_14H_PLCT0;
PLC_DATA=0X02;
PLC_ADDR=PLC_15H_ADC_D0;
PLC_DATA=0;
PLC_ADDR=PLC_16H_ADC_D1;
PLC_DATA=0;
PLC_ADDR=PLC_17H_ADC_DIN;
PLC_DATA=0;
PLC_ADDR=0x20;
PLC_DATA=0x33;
PLC_ADDR=0x21;
PLC_DATA=0x33;
PLC_ADDR=0x22;
PLC_DATA=0x33;
PLC_ADDR=0x23;
PLC_DATA=0x33;
PLC_ADDR=0x24;
PLC_DATA=0x33;
PLC_ADDR=0x25;
PLC_DATA=0x33;
PLC_ADDR=0x26;
PLC_DATA=0x33;
PLC_ADDR=0x27;
PLC_DATA=0x33;
PLC_ADDR=0x28;
PLC_DATA=0x33;
PLC_ADDR=0x29;
PLC_DATA=0x33;
PLC_ADDR=0x2a;
PLC_DATA=0x33;
PLC_ADDR=0x2b;
PLC_DATA=0x33;
PLC_ADDR=0x2c;
PLC_DATA=0x33;
PLC_ADDR=0x2d;
PLC_DATA=0x33;
PLC_ADDR=0x2e;
PLC_DATA=0x33;
PLC_ADDR=0x30;
PLC_DATA=0x55;
PLC_ADDR=0x31;
PLC_DATA=0x55;
PLC_ADDR=0x32;
PLC_DATA=0x55;
PLC_ADDR=0x33;
PLC_DATA=0x55;
PLC_ADDR=0x34;
PLC_DATA=0x55;
PLC_ADDR=0x35;
PLC_DATA=0x55;
PLC_ADDR=0x36;
PLC_DATA=0x55;
PLC_ADDR=0x37;
PLC_DATA=0x55;
PLC_ADDR=0x38;
PLC_DATA=0x55;
PLC_ADDR=0x39;
PLC_DATA=0x55;
PLC_ADDR=0x3a;
PLC_DATA=0x55;
PLC_ADDR=0x3b;
PLC_DATA=0x55;
PLC_ADDR=0x3c;
PLC_DATA=0x55;
PLC_ADDR=0x3d;
PLC_DATA=0x55;
PLC_ADDR=0x3e;
PLC_DATA=0x55;
PLC_ADDR=CSMAS;
PLC_DATA=0xC8; // 0xd3: //5.6mv; 0xb6
PLC_ADDR=CSMAT;
PLC_DATA=0xc9; //4MS 未选择基带成型发送,快速刷新
//PLC_DATA=0x20; //2MS 选择基带成型发送
PLC_ADDR=PLC_AFEC;
PLC_DATA=0X30; //Dac 1.6v(6db)
// PLC_ADDR=DIGTEST;
// PLC_DATA=0X40;
PLC_ADDR=FREQ_RX1;
PLC_DATA=0x02;
// PLC_DATA=0x01;
PLC_ADDR=FREQ_RX0;
PLC_DATA=0x1b;
// PLC_DATA=0xEC;
PLC_ADDR=0x49;
PLC_DATA=0x06;
PLC_ADDR=DKG;
PLC_DATA=0x0B;
PLC_ADDR=DIGTEST;
// PLC_DATA=0x00; // default
// PLC_DATA=0x08; // port B6=psk_RXD
PLC_DATA=0x04; // port B7=fsk_RXD
PLC_ADDR=MIXFWH;
PLC_DATA = 0x80;
// PLC_MOD=0x68; //开接收0X68
PLC_MOD=0;
PLC_RW=0x00;
}
void Ini_Plc_Tx(void)
{
PLC_RW=0x02;
PLC_ADDR=DAG;
PLC_DATA=0x1f; //0X3F
PLC_ADDR=0x06;
PLC_DATA=0X31; //
PLC_ADDR=0x11;
PLC_DATA=0X33; //ox13
PLC_ADDR=0x12;
PLC_DATA=0X13; //0x03
PLC_ADDR=FREQ_TX1;
PLC_DATA=0x02;//01
PLC_ADDR=FREQ_TX0;
PLC_DATA=0x06;//d8
PLC_ADDR=FREQ_TX2;
PLC_DATA=0x30; //06
PLC_ADDR=FREQ_TX3;
PLC_DATA=2;
//FREQ_TX0=0xE1;
// PLC_MOD=0x1f;
PLC_MOD=0x23;
//PLC_TXEN=1;
PLC_RW=0x00;
// PLC_RW=0x01;
//PLC_ADDR=DAG;
//testbyte=PLC_DATA;
//PLC_RW=0x00;
}
uchar Read_PlcReg(uchar RegAdd)
{
uchar ucA;
PLC_RW=0x01;
PLC_ADDR=RegAdd;
ucA=PLC_DATA;
PLC_RW=0x00;
return(ucA);
}
/************************************
** 函数原型: void Delay(uchar MS); **
** 功 能: 延时time=MS ms. **
************************************/
void Delay(uint MS)
{
uint aa;//,ucB;
uchar bb;
for(aa=0;aa<MS;aa++)
{
for(bb=0;bb<0xFC;)
{
bb++;
NOP();
}
for(bb=0;bb<0xFC;)
{
bb++;
NOP();
}
for(bb=0;bb<0xFC;)
{
bb++;
NOP();
}
for(bb=0;bb<0xFC;)
{
bb++;
NOP();
}
for(bb=0;bb<0xFc;)
{
bb++;
}
}
}
#define delay4t() NOP();NOP();NOP();NOP()
void delay6t()
{
NOP();
}
void delay7t()
{
NOP();
NOP();
}
void delay2_5us(void)
{
NOP();NOP();NOP();NOP();NOP();
NOP();NOP();NOP();NOP();NOP();
NOP();NOP();NOP();NOP();NOP();
NOP();NOP();NOP();NOP();NOP();
}
// 1位发送间隔时间 66.7uS == 667T
void DelayBit() // 109x6=654 + 13T = 667T
{
uchar bb;
for(bb=108;bb!=0;bb--) //每次6T
{
NOP();
}
NOP();
NOP();
NOP();
NOP();
NOP();
}
void plc_restart_sync()
{
plc_restart();
}
void Sum_DM21_Sync(uchar offset )
{
uchar ucS1,ucS0;
switch(offset)
{
case 0 :
ucS1=Bit1Num_T[2];
ucS1+=Bit1Num_T[4];
ucS1+=Bit1Num_T[5];
ucS1+=Bit1Num_T[6];
ucS0=Bit1Num_T[0];
ucS0+=Bit1Num_T[1];
ucS0+=Bit1Num_T[3];
ucS1+=Bit1Num_T[9];
ucS1+=Bit1Num_T[11];
ucS1+=Bit1Num_T[12];
ucS1+=Bit1Num_T[13];
ucS0+=Bit1Num_T[7];
ucS0+=Bit1Num_T[8];
ucS0+=Bit1Num_T[10];
ucS1+=Bit1Num_T[16];
ucS1+=Bit1Num_T[18];
ucS1+=Bit1Num_T[19];
ucS1+=Bit1Num_T[20];
ucS0+=Bit1Num_T[14];
ucS0+=Bit1Num_T[15];
ucS0+=Bit1Num_T[17];
ZXDM=ucS1+72-ucS0;
break;
case 1 :
ucS1=Bit1Num_T[3];
ucS1+=Bit1Num_T[5];
ucS1+=Bit1Num_T[6];
ucS1+=Bit1Num_T[7];
ucS0=Bit1Num_T[1];
ucS0+=Bit1Num_T[2];
ucS0+=Bit1Num_T[4];
ucS1+=Bit1Num_T[10];
ucS1+=Bit1Num_T[12];
ucS1+=Bit1Num_T[13];
ucS1+=Bit1Num_T[14];
ucS0+=Bit1Num_T[8];
ucS0+=Bit1Num_T[9];
ucS0+=Bit1Num_T[11];
ucS1+=Bit1Num_T[17];
ucS1+=Bit1Num_T[19];
ucS1+=Bit1Num_T[20];
ucS1+=Bit1Num_T[21];
ucS0+=Bit1Num_T[15];
ucS0+=Bit1Num_T[16];
ucS0+=Bit1Num_T[18];
ZXDM=ucS1+72-ucS0;
break;
case 2 :
ucS1=Bit1Num_T[4];
ucS1+=Bit1Num_T[6];
ucS1+=Bit1Num_T[7];
ucS1+=Bit1Num_T[8];
ucS0=Bit1Num_T[2];
ucS0+=Bit1Num_T[3];
ucS0+=Bit1Num_T[5];
ucS1+=Bit1Num_T[11];
ucS1+=Bit1Num_T[13];
ucS1+=Bit1Num_T[14];
ucS1+=Bit1Num_T[15];
ucS0+=Bit1Num_T[9];
ucS0+=Bit1Num_T[10];
ucS0+=Bit1Num_T[12];
ucS1+=Bit1Num_T[18];
ucS1+=Bit1Num_T[20];
ucS1+=Bit1Num_T[21];
ucS1+=Bit1Num_T[22];
ucS0+=Bit1Num_T[16];
ucS0+=Bit1Num_T[17];
ucS0+=Bit1Num_T[19];
ZXDM=ucS1+72-ucS0;
break;
}
if(ZXDM>168)
ZXDM=255-ZXDM;
FXDM=168-ZXDM;
}
void Sum_DM21_Sync2(uchar offset )
{
uchar ucS1,ucS0;
switch(offset)
{
case 0 :
ucS1=Bit1Num_T[2+RECV_BITS];
ucS1+=Bit1Num_T[4+RECV_BITS];
ucS1+=Bit1Num_T[5+RECV_BITS];
ucS1+=Bit1Num_T[6+RECV_BITS];
ucS0=Bit1Num_T[0+RECV_BITS];
ucS0+=Bit1Num_T[1+RECV_BITS];
ucS0+=Bit1Num_T[3+RECV_BITS];
ucS1+=Bit1Num_T[9+RECV_BITS];
ucS1+=Bit1Num_T[11+RECV_BITS];
ucS1+=Bit1Num_T[12+RECV_BITS];
ucS1+=Bit1Num_T[13+RECV_BITS];
ucS0+=Bit1Num_T[7+RECV_BITS];
ucS0+=Bit1Num_T[8+RECV_BITS];
ucS0+=Bit1Num_T[10+RECV_BITS];
ucS1+=Bit1Num_T[16+RECV_BITS];
ucS1+=Bit1Num_T[18+RECV_BITS];
ucS1+=Bit1Num_T[19+RECV_BITS];
ucS1+=Bit1Num_T[20+RECV_BITS];
ucS0+=Bit1Num_T[14+RECV_BITS];
ucS0+=Bit1Num_T[15+RECV_BITS];
ucS0+=Bit1Num_T[17+RECV_BITS];
ZXDM=ucS1+72-ucS0;
break;
case 1 :
ucS1=Bit1Num_T[3+RECV_BITS];
ucS1+=Bit1Num_T[5+RECV_BITS];
ucS1+=Bit1Num_T[6+RECV_BITS];
ucS1+=Bit1Num_T[7+RECV_BITS];
ucS0=Bit1Num_T[1+RECV_BITS];
ucS0+=Bit1Num_T[2+RECV_BITS];
ucS0+=Bit1Num_T[4+RECV_BITS];
ucS1+=Bit1Num_T[10+RECV_BITS];
ucS1+=Bit1Num_T[12+RECV_BITS];
ucS1+=Bit1Num_T[13+RECV_BITS];
ucS1+=Bit1Num_T[14+RECV_BITS];
ucS0+=Bit1Num_T[8+RECV_BITS];
ucS0+=Bit1Num_T[9+RECV_BITS];
ucS0+=Bit1Num_T[11+RECV_BITS];
ucS1+=Bit1Num_T[17+RECV_BITS];
ucS1+=Bit1Num_T[19+RECV_BITS];
ucS1+=Bit1Num_T[20+RECV_BITS];
ucS1+=Bit1Num_T[21+RECV_BITS];
ucS0+=Bit1Num_T[15+RECV_BITS];
ucS0+=Bit1Num_T[16+RECV_BITS];
ucS0+=Bit1Num_T[18+RECV_BITS];
ZXDM=ucS1+72-ucS0;
break;
case 2 :
ucS1=Bit1Num_T[4+RECV_BITS];
ucS1+=Bit1Num_T[6+RECV_BITS];
ucS1+=Bit1Num_T[7+RECV_BITS];
ucS1+=Bit1Num_T[8+RECV_BITS];
ucS0=Bit1Num_T[2+RECV_BITS];
ucS0+=Bit1Num_T[3+RECV_BITS];
ucS0+=Bit1Num_T[5+RECV_BITS];
ucS1+=Bit1Num_T[11+RECV_BITS];
ucS1+=Bit1Num_T[13+RECV_BITS];
ucS1+=Bit1Num_T[14+RECV_BITS];
ucS1+=Bit1Num_T[15+RECV_BITS];
ucS0+=Bit1Num_T[9+RECV_BITS];
ucS0+=Bit1Num_T[10+RECV_BITS];
ucS0+=Bit1Num_T[12+RECV_BITS];
ucS1+=Bit1Num_T[18+RECV_BITS];
ucS1+=Bit1Num_T[20+RECV_BITS];
ucS1+=Bit1Num_T[21+RECV_BITS];
ucS1+=Bit1Num_T[22+RECV_BITS];
ucS0+=Bit1Num_T[16+RECV_BITS];
ucS0+=Bit1Num_T[17+RECV_BITS];
ucS0+=Bit1Num_T[19+RECV_BITS];
ZXDM=ucS1+72-ucS0;
break;
}
if(ZXDM>168)
ZXDM=255-ZXDM;
FXDM=168-ZXDM;
}
void Sum_DM21_Sync3(uchar offset )
{
uchar ucS1,ucS0;
switch(offset)
{
case 0 :
ucS1=Bit1Num_T1[2];
ucS1+=Bit1Num_T1[4];
ucS1+=Bit1Num_T1[5];
ucS1+=Bit1Num_T1[6];
ucS0=Bit1Num_T1[0];
ucS0+=Bit1Num_T1[1];
ucS0+=Bit1Num_T1[3];
ucS1+=Bit1Num_T1[9];
ucS1+=Bit1Num_T1[11];
ucS1+=Bit1Num_T1[12];
ucS1+=Bit1Num_T1[13];
ucS0+=Bit1Num_T1[7];
ucS0+=Bit1Num_T1[8];
ucS0+=Bit1Num_T1[10];
ucS1+=Bit1Num_T1[16];
ucS1+=Bit1Num_T1[18];
ucS1+=Bit1Num_T1[19];
ucS1+=Bit1Num_T1[20];
ucS0+=Bit1Num_T1[14];
ucS0+=Bit1Num_T1[15];
ucS0+=Bit1Num_T1[17];
ZXDM=ucS1+72-ucS0;
break;
case 1 :
ucS1=Bit1Num_T1[3];
ucS1+=Bit1Num_T1[5];
ucS1+=Bit1Num_T1[6];
ucS1+=Bit1Num_T1[7];
ucS0=Bit1Num_T1[1];
ucS0+=Bit1Num_T1[2];
ucS0+=Bit1Num_T1[4];
ucS1+=Bit1Num_T1[10];
ucS1+=Bit1Num_T1[12];
ucS1+=Bit1Num_T1[13];
ucS1+=Bit1Num_T1[14];
ucS0+=Bit1Num_T1[8];
ucS0+=Bit1Num_T1[9];
ucS0+=Bit1Num_T1[11];
ucS1+=Bit1Num_T[17];
ucS1+=Bit1Num_T[19];
ucS1+=Bit1Num_T[20];
ucS1+=Bit1Num_T[21];
ucS0+=Bit1Num_T[15];
ucS0+=Bit1Num_T[16];
ucS0+=Bit1Num_T[18];
ZXDM=ucS1+72-ucS0;
break;
case 2 :
ucS1=Bit1Num_T1[4];
ucS1+=Bit1Num_T1[6];
ucS1+=Bit1Num_T1[7];
ucS1+=Bit1Num_T1[8];
ucS0=Bit1Num_T1[2];
ucS0+=Bit1Num_T1[3];
ucS0+=Bit1Num_T1[5];
ucS1+=Bit1Num_T1[11];
ucS1+=Bit1Num_T1[13];
ucS1+=Bit1Num_T1[14];
ucS1+=Bit1Num_T1[15];
ucS0+=Bit1Num_T1[9];
ucS0+=Bit1Num_T1[10];
ucS0+=Bit1Num_T1[12];
ucS1+=Bit1Num_T1[18];
ucS1+=Bit1Num_T1[20];
ucS1+=Bit1Num_T1[21];
ucS1+=Bit1Num_T1[22];
ucS0+=Bit1Num_T1[16];
ucS0+=Bit1Num_T1[17];
ucS0+=Bit1Num_T1[19];
ZXDM=ucS1+72-ucS0;
break;
}
if(ZXDM>168)
ZXDM=255-ZXDM;
FXDM=168-ZXDM;
}
void Sum_DM21_Sync4(uchar offset )
{
uchar ucS1,ucS0;
switch(offset)
{
case 0 :
ucS1=Bit1Num_T1[2+RECV_BITS];
ucS1+=Bit1Num_T1[4+RECV_BITS];
ucS1+=Bit1Num_T1[5+RECV_BITS];
ucS1+=Bit1Num_T1[6+RECV_BITS];
ucS0=Bit1Num_T1[0+RECV_BITS];
ucS0+=Bit1Num_T1[1+RECV_BITS];
ucS0+=Bit1Num_T1[3+RECV_BITS];
ucS1+=Bit1Num_T1[9+RECV_BITS];
ucS1+=Bit1Num_T1[11+RECV_BITS];
ucS1+=Bit1Num_T1[12+RECV_BITS];
ucS1+=Bit1Num_T1[13+RECV_BITS];
ucS0+=Bit1Num_T1[7+RECV_BITS];
ucS0+=Bit1Num_T1[8+RECV_BITS];
ucS0+=Bit1Num_T1[10+RECV_BITS];
ucS1+=Bit1Num_T1[16+RECV_BITS];
ucS1+=Bit1Num_T1[18+RECV_BITS];
ucS1+=Bit1Num_T1[19+RECV_BITS];
ucS1+=Bit1Num_T1[20+RECV_BITS];
ucS0+=Bit1Num_T1[14+RECV_BITS];
ucS0+=Bit1Num_T1[15+RECV_BITS];
ucS0+=Bit1Num_T1[17+RECV_BITS];
ZXDM=ucS1+72-ucS0;
break;
case 1 :
ucS1=Bit1Num_T1[3+RECV_BITS];
ucS1+=Bit1Num_T1[5+RECV_BITS];
ucS1+=Bit1Num_T1[6+RECV_BITS];
ucS1+=Bit1Num_T1[7+RECV_BITS];
ucS0=Bit1Num_T1[1+RECV_BITS];
ucS0+=Bit1Num_T1[2+RECV_BITS];
ucS0+=Bit1Num_T1[4+RECV_BITS];
ucS1+=Bit1Num_T1[10+RECV_BITS];
ucS1+=Bit1Num_T1[12+RECV_BITS];
ucS1+=Bit1Num_T1[13+RECV_BITS];
ucS1+=Bit1Num_T1[14+RECV_BITS];
ucS0+=Bit1Num_T1[8+RECV_BITS];
ucS0+=Bit1Num_T1[9+RECV_BITS];
ucS0+=Bit1Num_T1[11+RECV_BITS];
ucS1+=Bit1Num_T1[17+RECV_BITS];
ucS1+=Bit1Num_T1[19+RECV_BITS];
ucS1+=Bit1Num_T1[20+RECV_BITS];
ucS1+=Bit1Num_T1[21+RECV_BITS];
ucS0+=Bit1Num_T1[15+RECV_BITS];
ucS0+=Bit1Num_T1[16+RECV_BITS];
ucS0+=Bit1Num_T1[18+RECV_BITS];
ZXDM=ucS1+72-ucS0;
break;
case 2 :
ucS1=Bit1Num_T1[4+RECV_BITS];
ucS1+=Bit1Num_T1[6+RECV_BITS];
ucS1+=Bit1Num_T1[7+RECV_BITS];
ucS1+=Bit1Num_T1[8+RECV_BITS];
ucS0=Bit1Num_T1[2+RECV_BITS];
ucS0+=Bit1Num_T1[3+RECV_BITS];
ucS0+=Bit1Num_T1[5+RECV_BITS];
ucS1+=Bit1Num_T1[11+RECV_BITS];
ucS1+=Bit1Num_T1[13+RECV_BITS];
ucS1+=Bit1Num_T1[14+RECV_BITS];
ucS1+=Bit1Num_T1[15+RECV_BITS];
ucS0+=Bit1Num_T1[9+RECV_BITS];
ucS0+=Bit1Num_T1[10+RECV_BITS];
ucS0+=Bit1Num_T1[12+RECV_BITS];
ucS1+=Bit1Num_T1[18+RECV_BITS];
ucS1+=Bit1Num_T1[20+RECV_BITS];
ucS1+=Bit1Num_T1[21+RECV_BITS];
ucS1+=Bit1Num_T1[22+RECV_BITS];
ucS0+=Bit1Num_T1[16+RECV_BITS];
ucS0+=Bit1Num_T1[17+RECV_BITS];
ucS0+=Bit1Num_T1[19+RECV_BITS];
ZXDM=ucS1+72-ucS0;
break;
}
if(ZXDM>168)
ZXDM=255-ZXDM;
FXDM=168-ZXDM;
}
sbit Recv_Bit()
{
if(ZXDM>84)
{
//NOP();
return(1);
}
else
{
return(0);
}
}
/**************
*******21PN
*******数据1扩频发送**********/
void TX1_PN23(void)
{
TX_Bit1() ;//1 //多发1个无用的 0520
DelayBit();
TX_Bit1() ;//1 //多发1个无用的
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit0() ;//1
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit1() ;//1
DelayBit();//DelayEndBit();//1303
}
/**************
*******21PN 两位间发送间隔1332T
*******数据0扩频发送**********/
void TX0_PN23(void)
{
TX_Bit0() ;//1 多发1BIT 0520
DelayBit();
TX_Bit0() ;//1 多发1BIT
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit1() ;//0
DelayBit();
TX_Bit1() ;//0
DelayBit();
TX_Bit0() ;//1
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit0() ;//1
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit1() ;//0
DelayBit();
TX_Bit1() ;//0
DelayBit();
TX_Bit0() ;//1
DelayBit();
TX_Bit1() ;//1
DelayBit();
TX_Bit0() ;//1
DelayBit();
TX_Bit0() ;//0
DelayBit();
TX_Bit0() ;//0
DelayBit();;//DelayEndBit();//1303
}
//位间隔1998US
void tx_normal_data(void) /*发送正常数据*/
{
if(Plc_data_bit_cnt==0) /*此字节发送完*/
{
Plc_data_byte_cnt++;
Plc_data_bit_cnt=8; /*应发送8位,先减一后发送,所以为9;*/
if(t_nor_bit==1)
{
plc_byte_data=plc_data[Plc_data_byte_cnt]; /*取要发送的数据,有0x09af*/
if(Plc_data_byte_cnt==Plc_data_len) /*全部发送完*/
{
t_nor_bit=0;
t_end_bit=1;
S_LED=0; //最后一位扩频位尚未发送
return;
}
}
else
{
plc_byte_data=0xff;
if(Plc_data_byte_cnt==2)
{
t_nor_bit=1;
Plc_data_byte_cnt=0;
plc_byte_data=plc_data[Plc_data_byte_cnt];
}
}
}
else if (Plc_data_bit_cnt != 8)
{
plc_byte_data<<=1;
}
if(plc_byte_data&0x80)
Plc_Tx_Bit=1;
else
Plc_Tx_Bit=0;
Plc_data_bit_cnt--; /*还应发送几位*/
}
/*******************接收载波数据******************/
void rcv_normal_data(void) /*正常接收*/
{
uchar i;
Plc_data_bit_cnt--; /*还剩几位*/
if((Plc_data_byte_cnt+1)==1)
{
if (Plc_data_bit_cnt==0)
NOP();
}
if(Plc_data_bit_cnt!=0) /*未接收完一个字节*/
return;
Plc_data_bit_cnt=8;
plc_data[Plc_data_byte_cnt]=plc_byte_data; /*存储一个字节*/
Plc_data_byte_cnt++;
if(Plc_data_byte_cnt==1)
{// Plc_data_len=plc_data[6]+8;
if(plc_data[0]>=MaxPlcL)
{
plc_restart();
return;
}
}
else
{
if((Plc_data_byte_cnt+1)==9)
NOP();
if((Plc_data_byte_cnt+1)>=plc_data[0])// plc_data[1]) /*如果全部接收完*/
{
Rx_status='R';
r_sync_bit=0;
plc_byte_data=0;
R_LED = 1;
plc_recv_finished();
}
} /*还未接收完*/
//Plc_data_bit_cnt=8;
}
/*加call指令,本函数647T */
void Recv_Plc_8Bit(void) //667采样8次,83T和84T间隔采样
{
uchar ucA;
Plc_Samples_byte=0;
Plc_Samples_bit1_cnt=0; /* 3T */
delay2_5us();
delay7t();
delay7t();
Plc_Samples_byte<<=1; /* 2T */
if(PLC_FSK_RXD) /* 5T */
{
Plc_Samples_byte|=0x01;
Plc_Samples_bit1_cnt++;
}
else
{
NOP();
NOP();
}
delay2_5us();
delay2_5us();
delay2_5us();
NOP();
Plc_Samples_byte<<=1;
if(PLC_FSK_RXD)
{
Plc_Samples_byte|=0x01;
Plc_Samples_bit1_cnt++;
}
else
{
NOP();
NOP();
}
delay2_5us();
delay2_5us();
delay2_5us();
NOP();
NOP();
Plc_Samples_byte<<=1;
if(PLC_FSK_RXD)
{
Plc_Samples_byte|=0x01;
Plc_Samples_bit1_cnt++;
}
else
{
NOP();
NOP();
}
delay2_5us();
delay2_5us();
delay2_5us();
NOP();
Plc_Samples_byte<<=1;
if(PLC_FSK_RXD)
{
Plc_Samples_byte|=0x01;
Plc_Samples_bit1_cnt++;
}
else
{
NOP();
NOP();
}
delay2_5us();
delay2_5us();
delay2_5us();
NOP();
NOP();
Plc_Samples_byte<<=1;
if(PLC_FSK_RXD)
{
Plc_Samples_byte|=0x01;
Plc_Samples_bit1_cnt++;
}
else
{
NOP();
NOP();
}
delay2_5us();
delay2_5us();
delay2_5us();
NOP();
Plc_Samples_byte<<=1;
if(PLC_FSK_RXD)
{
Plc_Samples_byte|=0x01;
Plc_Samples_bit1_cnt++;
}
else
{
NOP();
NOP();
}
delay2_5us();
delay2_5us();
delay2_5us();
NOP();
NOP();
Plc_Samples_byte<<=1;
if(PLC_FSK_RXD)
{
Plc_Samples_byte|=0x01;
Plc_Samples_bit1_cnt++;
}
else
{
NOP();
NOP();
}
delay2_5us();
delay2_5us();
delay2_5us();
NOP();
Plc_Samples_byte<<=1;
if(PLC_FSK_RXD)
{
Plc_Samples_byte|=0x01;
Plc_Samples_bit1_cnt++;
}
else
{
NOP();
NOP();
}
delay7t();
NOP();
NOP();
NOP();
}
void Recv_23Pn(void)
{
/* 647T +3T +4T +13T =667T == one bit time */
Recv_Plc_8Bit();
Bit1Num_T[0]=Plc_Samples_bit1_cnt; /* 3T */
BitData_T[0]=Plc_Samples_byte; /* 4T */
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[1]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[1]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[2]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[2]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[3]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[3]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[4]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[4]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[5]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[5]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[6]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[6]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[7]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[7]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[8]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[8]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[9]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[9]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[10]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[10]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[11]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[11]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[12]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[12]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[13]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[13]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[14]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[14]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[15]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[15]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[16]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[16]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[17]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[17]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[18]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[18]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[19]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[19]=Plc_Samples_byte;
delay4t();
PLC_RW=0x01; /* 2T */
PLC_ADDR=0x51; /* 2T */
RSSIV=PLC_DATA; /* 3T */
PLC_RW=0x00; /* 1T */
NOP();
Recv_Plc_8Bit();
Bit1Num_T[20]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[20]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[21]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[21]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[22]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[22]=Plc_Samples_byte;
delay7t();
delay6t();
}
void Recv_1_23Pn(void)
{
/* 647T +3T +4T +13T =667T == one bit time */
Recv_Plc_8Bit();
Bit1Num_T[RECV_BITS]=Plc_Samples_bit1_cnt; /* 3T */
BitData_T[RECV_BITS]=Plc_Samples_byte; /* 4T */
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[1+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[1+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[2+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[2+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[3+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[3+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[4+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[4+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[5+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[5+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[6+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[6+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[7+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[7+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[8+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[8+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[9+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[9+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[10+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[10+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[11+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[11+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[12+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[12+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[13+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[13+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[14+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[14+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[15+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[15+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[16+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[16+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[17+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[17+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[18+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[18+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[19+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[19+RECV_BITS]=Plc_Samples_byte;
delay4t();
PLC_RW=0x01; /* 2T */
PLC_ADDR=0x51; /* 2T */
RSSIV=PLC_DATA; /* 3T */
PLC_RW=0x00; /* 1T */
NOP();
Recv_Plc_8Bit();
Bit1Num_T[20+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[20+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[21+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[21+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[22+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[22+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
}
void Recv_2_23Pn(void)
{
/* 647T +3T +4T +13T =667T == one bit time */
Recv_Plc_8Bit();
Bit1Num_T[0]=Plc_Samples_bit1_cnt; /* 3T */
BitData_T[0]=Plc_Samples_byte; /* 4T */
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[1]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[1]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[2]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[2]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[3]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[3]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[4]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[4]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[5]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[5]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[6]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[6]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[7]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[7]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[8]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[8]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[9]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[9]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[10]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[10]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[11]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[11]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[12]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[12]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[13]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[13]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[14]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[14]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[15]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[15]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[16]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[16]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[17]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[17]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[18]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[18]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[19]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[19]=Plc_Samples_byte;
delay4t();
PLC_RW=0x01; /* 2T */
PLC_ADDR=0x51; /* 2T */
RSSIV=PLC_DATA; /* 3T */
PLC_RW=0x00; /* 1T */
NOP();
Recv_Plc_8Bit();
Bit1Num_T[20]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[20]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[21]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[21]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[22]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[22]=Plc_Samples_byte;
delay7t();
delay6t();
}
void Recv_3_23Pn(void)
{
/* 647T +3T +4T +13T =667T == one bit time */
Recv_Plc_8Bit();
Bit1Num_T[RECV_BITS]=Plc_Samples_bit1_cnt; /* 3T */
BitData_T[RECV_BITS]=Plc_Samples_byte; /* 4T */
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[1+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[1+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[2+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[2+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[3+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[3+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[4+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[4+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[5+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[5+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[6+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[6+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[7+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[7+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[8+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[8+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[9+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[9+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[10+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[10+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[11+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[11+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[12+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[12+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[13+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[13+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[14+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[14+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[15+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[15+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[16+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[16+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[17+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[17+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[18+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[18+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[19+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[19+RECV_BITS]=Plc_Samples_byte;
delay4t();
PLC_RW=0x01; /* 2T */
PLC_ADDR=0x51; /* 2T */
RSSIV=PLC_DATA; /* 3T */
PLC_RW=0x00; /* 1T */
NOP();
Recv_Plc_8Bit();
Bit1Num_T[20+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[20+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[21+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[21+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
Recv_Plc_8Bit();
Bit1Num_T[22+RECV_BITS]=Plc_Samples_bit1_cnt; //1的个数
BitData_T[22+RECV_BITS]=Plc_Samples_byte;
delay7t();
delay6t();
}
void Zero_Time_adjust()
{
uchar ucA,ucB;
uint uiT_20ms;
// T16G1R_S.NumLong=0;
if(T16G1R_new.NumInt<T16G1R_old.NumInt)
{
uiT_20ms=65536-T16G1R_old.NumInt;
uiT_20ms+=T16G1R_new.NumInt;
}
else
uiT_20ms=T16G1R_new.NumInt-T16G1R_old.NumInt;
if((uiT_20ms>53500)||(uiT_20ms<46500))
{
uiT_20ms=0;
}
else
{
T16G1R_S.NumLong=0;
Zero_cnt++;
//
T16G1R_20ms[Zero_cnt].NumInt=uiT_20ms;
if(Zero_cnt>=Zero_Num)
{
Zero_cnt=Zero_Num-1;
for(ucA=0;ucA<Zero_Num;ucA++)
{
T16G1R_20ms[ucA].NumInt=T16G1R_20ms[ucA+1].NumInt;
T16G1R_S.NumLong+=T16G1R_20ms[ucA+1].NumInt;
}
if((T16G1R_S.NumChar[0]&0X03)<3) //四舍5入处理
T16G1R_S.NumLong=T16G1R_S.NumLong/Zero_Num; //每次过零用的时间T0
else
{
T16G1R_S.NumLong=T16G1R_S.NumLong/Zero_Num;
T16G1R_S.NumLong++;
}
if(Plc_ZeroMode!=1)
Plc_ZeroMode=1;
}
}
}
void T16G1Int_Proc(void)
{
if(Plc_Mode==0)
{
if(Plc_ZeroMode==1)
{
IniT16G2(2);
T16G2IF=0;
T16G2IE=1;
Work_step=1;
}
}
else if(Plc_Mode=='T' && Plc_ZeroMode == 1)
{
if(Work_step!=2)
{
IniT16G2(2);
T16G2IF=0;
T16G2IE=1;
Work_step=1;
}
else
{ //T16G1IE=0;
}
}
T16G1R_old.NumInt=T16G1R_new.NumInt;
T16G1R_new.NumChar[0]=T16G1RL;
T16G1R_new.NumChar[1]=T16G1RH;
Zero_Time_adjust();
// Zero_cnt=0;
Work_step=0;
// Plc_Mode='R';
}
void T16G2Int_Proc(void)
{
if(Plc_Mode=='T')
{
if(Work_step==2)
{
PLC_MOD=0x23;
PLC_TX;
if(t_end_bit==0) //
{
trans_step_next();
if(Plc_Tx_first_Bit)
TX0_PN23();
else
TX1_PN23();
DelayBit();
if(Plc_Tx_Second_Bit)
TX0_PN23();
else
TX1_PN23();
DelayBit();
if(Plc_Tx_Third_Bit)
TX0_PN23();
else
TX1_PN23();
DelayBit();
if(Plc_Tx_Forth_Bit)
TX0_PN23();
else
TX1_PN23();
tx_normal_data();
Plc_Tx_first_Bit = Plc_Tx_Bit;
tx_normal_data();
Plc_Tx_Second_Bit= Plc_Tx_Bit;
tx_normal_data();
Plc_Tx_Third_Bit = Plc_Tx_Bit;
tx_normal_data();
Plc_Tx_Forth_Bit= Plc_Tx_Bit;
PLC_MOD=0x00;
}
if(t_end_bit)
{
Plc_Mode=0;
t_nor_bit=0;
Plc_data_len=0;
R_LED=1;
T16G1IE=1;
T16G2IE=0;
PLC_MOD=0X59;
}
PLC_RX;
}
else // if(Work_step==1) //
{
Work_step=2;
PLC_MOD=0x23;
PLC_TX;
trans_step_next();
if(Plc_Tx_first_Bit)
TX0_PN23();
else
TX1_PN23();
DelayBit();
if(Plc_Tx_Second_Bit)
TX0_PN23();
else
TX1_PN23();
DelayBit();
if(Plc_Tx_Third_Bit)
TX0_PN23();
else
TX1_PN23();
DelayBit();
if(Plc_Tx_Forth_Bit)
TX0_PN23();
else
TX1_PN23();
tx_normal_data();
Plc_Tx_first_Bit = Plc_Tx_Bit;
tx_normal_data();
Plc_Tx_Second_Bit= Plc_Tx_Bit;
tx_normal_data();
Plc_Tx_Third_Bit = Plc_Tx_Bit;
tx_normal_data();
Plc_Tx_Forth_Bit= Plc_Tx_Bit;
delay6t();
PLC_RX;
PLC_MOD=0;
T16G1IE=0;
}
}
else if(Plc_Mode=='R')
{
Rec_Zero_bz=1;
trans_step_next();
if(Work_step==2)
{
PLC_MOD=0x59;
Recv_23Pn();
DelayBit();
Recv_1_23Pn();
DelayBit();
Recv_2_23Pn();
DelayBit();
Recv_3_23Pn();
PLC_MOD=0x00; //0720
}
else // if(Work_step==1) //
{
PLC_MOD=0x59;
// PLC_RX;
Recv_23Pn();
DelayBit();
Recv_1_23Pn();
DelayBit();
Recv_2_23Pn();
DelayBit();
Recv_3_23Pn();
PLC_MOD=0x00; //0720
Work_step=2;
}
}
else if(Plc_Mode==0)
{
PLC_MOD=0x59;
trans_step_next();
Recv_23Pn();
DelayBit();
Recv_1_23Pn();
DelayBit();
Recv_2_23Pn();
DelayBit();
Recv_3_23Pn();
PLC_MOD=0x00; //0720
Plc_Mode='F';
Rec_Zero_bz=1;
Sync_Step = 0;
T16G1IE=0;
}
else if(Plc_Mode=='F')
{
PLC_MOD=0x59;
trans_step_next();
Recv_23Pn();
DelayBit();
Recv_1_23Pn();
DelayBit();
Recv_2_23Pn();
DelayBit();
Recv_3_23Pn();
PLC_MOD=0x00; //0720
Plc_Mode='F';
Rec_Zero_bz=1;
}
if(T16G1IF)
{
T16G1R_old.NumInt=T16G1R_new.NumInt;
T16G1R_new.NumChar[0]=T16G1RL;
T16G1R_new.NumChar[1]=T16G1RH;
//Zero_cnt++;
Zero_Time_adjust();
T16G1IF=0;
}
}
void INTS(void) interrupt
{
if((T16G2IF)&&(T16G2IE))
{
T16G2Int_Proc();
T16G2IF=0;
}
if((T16G1IF)&&(T16G1IE))
{
T16G1Int_Proc();
T16G1IF=0;
}
}
void Sync_offset(uchar off)
{
switch(off)
{
case 0:
do_left_shift_1bit(0);
case 1:
do_left_shift_1bit(1);
case 2:
do_left_shift_1bit(2);
default:
do_left_shift_1bit(3);
do_left_shift_1bit(4);
do_left_shift_1bit(5);
do_left_shift_1bit(6);
do_left_shift_1bit(7);
do_left_shift_1bit(8);
do_left_shift_1bit(9);
do_left_shift_1bit(10);
do_left_shift_1bit(11);
do_left_shift_1bit(12);
do_left_shift_1bit(13);
do_left_shift_1bit(14);
do_left_shift_1bit(15);
do_left_shift_1bit(16);
do_left_shift_1bit(17);
do_left_shift_1bit(18);
do_left_shift_1bit(19);
do_left_shift_1bit(20);
do_left_shift_1bit(21);
do_left_shift_1bit(22);
break;
}
}
void Sync_adjust(void)
{
uchar ucB,ucC;
for(ucB=0;ucB<SYCl_offset;ucB++) //约13335T
{
if (0 == SYM_offset)
Sync_offset(0);
if (1 == SYM_offset)
Sync_offset(1);
if (2 == SYM_offset)
Sync_offset(2);
else
Sync_offset(2);
}
}
void Sync_offset2(uchar off)
{
switch(off)
{
case 0:
do_left_shift_1bit(0+RECV_BITS);
case 1:
do_left_shift_1bit(1+RECV_BITS);
case 2:
do_left_shift_1bit(2+RECV_BITS);
default:
do_left_shift_1bit(3+RECV_BITS);
do_left_shift_1bit(4+RECV_BITS);
do_left_shift_1bit(5+RECV_BITS);
do_left_shift_1bit(6+RECV_BITS);
do_left_shift_1bit(7+RECV_BITS);
do_left_shift_1bit(8+RECV_BITS);
do_left_shift_1bit(9+RECV_BITS);
do_left_shift_1bit(10+RECV_BITS);
do_left_shift_1bit(11+RECV_BITS);
do_left_shift_1bit(12+RECV_BITS);
do_left_shift_1bit(13+RECV_BITS);
do_left_shift_1bit(14+RECV_BITS);
do_left_shift_1bit(15+RECV_BITS);
do_left_shift_1bit(16+RECV_BITS);
do_left_shift_1bit(17+RECV_BITS);
do_left_shift_1bit(18+RECV_BITS);
do_left_shift_1bit(19+RECV_BITS);
do_left_shift_1bit(20+RECV_BITS);
do_left_shift_1bit(21+RECV_BITS);
do_left_shift_1bit(22+RECV_BITS);
break;
}
}
void Sync_adjust2(void)
{
uchar ucB,ucC;
for(ucB=0;ucB<SYCl_offset2;ucB++) //约13335T
{
if (0 == SYM_offset2)
Sync_offset2(0);
if (1 == SYM_offset2)
Sync_offset2(1);
if (2 == SYM_offset2)
Sync_offset2(2);
else
Sync_offset2(2);
}
}
void Sync_offset3(uchar off)
{
switch(off)
{
case 0:
do_left_shift_1bit_1(0);
case 1:
do_left_shift_1bit_1(1);
case 2:
do_left_shift_1bit_1(2);
default:
do_left_shift_1bit_1(3);
do_left_shift_1bit_1(4);
do_left_shift_1bit_1(5);
do_left_shift_1bit_1(6);
do_left_shift_1bit_1(7);
do_left_shift_1bit_1(8);
do_left_shift_1bit_1(9);
do_left_shift_1bit_1(10);
do_left_shift_1bit_1(11);
do_left_shift_1bit_1(12);
do_left_shift_1bit_1(13);
do_left_shift_1bit_1(14);
do_left_shift_1bit_1(15);
do_left_shift_1bit_1(16);
do_left_shift_1bit_1(17);
do_left_shift_1bit_1(18);
do_left_shift_1bit_1(19);
do_left_shift_1bit_1(20);
do_left_shift_1bit_1(21);
do_left_shift_1bit_1(22);
break;
}
}
void Sync_adjust3(void)
{
uchar ucB,ucC;
for(ucB=0;ucB<SYCl_offset3;ucB++) //约13335T
{
if (0 == SYM_offset3)
Sync_offset3(0);
if (1 == SYM_offset3)
Sync_offset3(1);
if (2 == SYM_offset3)
Sync_offset3(2);
else
Sync_offset3(2);
}
}
void Sync_offset4(uchar off)
{
switch(off)
{
case 0:
do_left_shift_1bit_1(0+RECV_BITS);
case 1:
do_left_shift_1bit_1(1+RECV_BITS);
case 2:
do_left_shift_1bit_1(2+RECV_BITS);
default:
do_left_shift_1bit_1(3+RECV_BITS);
do_left_shift_1bit_1(4+RECV_BITS);
do_left_shift_1bit_1(5+RECV_BITS);
do_left_shift_1bit_1(6+RECV_BITS);
do_left_shift_1bit_1(7+RECV_BITS);
do_left_shift_1bit_1(8+RECV_BITS);
do_left_shift_1bit_1(9+RECV_BITS);
do_left_shift_1bit_1(10+RECV_BITS);
do_left_shift_1bit_1(11+RECV_BITS);
do_left_shift_1bit_1(12+RECV_BITS);
do_left_shift_1bit_1(13+RECV_BITS);
do_left_shift_1bit_1(14+RECV_BITS);
do_left_shift_1bit_1(15+RECV_BITS);
do_left_shift_1bit_1(16+RECV_BITS);
do_left_shift_1bit_1(17+RECV_BITS);
do_left_shift_1bit_1(18+RECV_BITS);
do_left_shift_1bit_1(19+RECV_BITS);
do_left_shift_1bit_1(20+RECV_BITS);
do_left_shift_1bit_1(21+RECV_BITS);
do_left_shift_1bit_1(22+RECV_BITS);
break;
}
}
void Sync_adjust4(void)
{
uchar ucB,ucC;
for(ucB=0;ucB<SYCl_offset4;ucB++) //约13335T
{
if (0 == SYM_offset4)
Sync_offset4(0);
if (1 == SYM_offset4)
Sync_offset4(1);
if (2 == SYM_offset4)
Sync_offset4(2);
else
Sync_offset4(2);
}
}
void _Plc_RecvProc(uchar offset)
{
//if(1/*Sync_Step=='E'*/)
if (offset == 0) {
Sync_adjust();
Sum_DM21_Sync(SYM_offset);
}else if (offset == 1){
Sync_adjust2();
Sum_DM21_Sync2(SYM_offset2);
}else if (offset == 2){
Sync_adjust3();
Sum_DM21_Sync3(SYM_offset3);
}else if (offset == 2){
Sync_adjust4();
Sum_DM21_Sync4(SYM_offset4);
}
sync_word_l<<=1;
if(plc_byte_data&0x80)
{
sync_word_l|=0x01;
}
plc_byte_data<<=1;
if(Recv_Bit())
plc_byte_data|=0x01;
//ZXDM_buf[Sync_bit1_cnt]=ZXDM;
//RSSIV_buf[Sync_bit1_cnt]=RSSIV;
if(r_sync_bit==1) //如果收到桢同步信号09
{
rcv_normal_data(); //
return;
}
Sync_bit1_cnt++;
if(((plc_byte_data&0x01)==0)&&(sync_word_l!=0xff))
{
plc_restart();
R_LED=0;
return;
}
if((plc_byte_data==0xaa)&&(sync_word_l==0xff)) //Sync_Char
{
Plc_data_bit_cnt=8; //收到位数标志置为9,除此位是先减一后接收外,其它都是先接收后减一,所以其它应为8;
r_sync_bit=1; //收到桢同步标志置1
// r_func1_bit=0; //准备收第一个字节FUNC
Plc_data_byte_cnt=0;
//R_LED=1;
}
else {
if(Sync_bit1_cnt>=Sync_bit1_cnt_Max)
{
plc_restart();
R_LED=0;
IniT16G1(CCPMODE);
}
}
}
union SVR_INT_B08 t1, t2;
int test;
void Plc_RecvProc()
{
// T16G2IE = 0;
// t1.NumChar[0]=T16G1L;
// t1.NumChar[1] = T16G1H;
//test = 0xaa;
_Plc_RecvProc(0);
if (Sync_Step == 'E') {
_Plc_RecvProc(1);
}
if (Sync_Step == 'E') {
_Plc_RecvProc(2);
}
if (Sync_Step == 'E') {
_Plc_RecvProc(3);
}
// t2.NumChar[0]=T16G1L;
// t2.NumChar[1] = T16G1H;
// test = t2.NumInt - t1.NumInt;
//T16G2IE = 1;
}
//相位同步法1,每次移1BIT,移7次,每次都要按15个字节按字节移15次;共计算8*15=120次
void _Sync1_Proc(uchar offset)
{
uchar ucA,ucB,ucC;
Sum_Max=0;
Sum_FXMax=0; //0720
if (offset == 0) {
SYM_offset=0;
SYCl_offset=0;
}else {
SYM_offset2=0;
SYCl_offset2=0;
}
//BitData_T[23+offset]=BitData_T[0+offset];
for(ucB=0;ucB<8;ucB++) //约13335T
{
for(ucA=0;ucA<3;ucA++)
{
if (offset == 0) {
Sum_DM21_Sync(ucA);
if(ZXDM>Sum_Max)
{
Sum_Max=ZXDM;
SYM_offset=ucA;
SYCl_offset=ucB;
}
}else{
Sum_DM21_Sync2(ucA);
if(ZXDM>Sum_Max)
{
Sum_Max=ZXDM;
SYM_offset2=ucA;
SYCl_offset2=ucB;
}
}
// else 6 nop
if(FXDM>Sum_FXMax)
{
Sum_FXMax=FXDM;
}
}
if (offset == 0)
{
do_left_shift_1bit(0);
do_left_shift_1bit(1);
do_left_shift_1bit(2);
do_left_shift_1bit(3);
do_left_shift_1bit(4);
do_left_shift_1bit(5);
do_left_shift_1bit(6);
do_left_shift_1bit(7);
do_left_shift_1bit(8);
do_left_shift_1bit(9);
do_left_shift_1bit(10);
do_left_shift_1bit(11);
do_left_shift_1bit(12);
do_left_shift_1bit(13);
do_left_shift_1bit(14);
do_left_shift_1bit(15);
do_left_shift_1bit(16);
do_left_shift_1bit(17);
do_left_shift_1bit(18);
do_left_shift_1bit(19);
do_left_shift_1bit(20);
do_left_shift_1bit(21);
do_left_shift_1bit(22);
//OFF_do(23);
}else{
do_left_shift_1bit(0+RECV_BITS);
do_left_shift_1bit(1+RECV_BITS);
do_left_shift_1bit(2+RECV_BITS);
do_left_shift_1bit(3+RECV_BITS);
do_left_shift_1bit(4+RECV_BITS);
do_left_shift_1bit(5+RECV_BITS);
do_left_shift_1bit(6+RECV_BITS);
do_left_shift_1bit(7+RECV_BITS);
do_left_shift_1bit(8+RECV_BITS);
do_left_shift_1bit(9+RECV_BITS);
do_left_shift_1bit(10+RECV_BITS);
do_left_shift_1bit(11+RECV_BITS);
do_left_shift_1bit(12+RECV_BITS);
do_left_shift_1bit(13+RECV_BITS);
do_left_shift_1bit(14+RECV_BITS);
do_left_shift_1bit(15+RECV_BITS);
do_left_shift_1bit(16+RECV_BITS);
do_left_shift_1bit(17+RECV_BITS);
do_left_shift_1bit(18+RECV_BITS);
do_left_shift_1bit(19+RECV_BITS);
do_left_shift_1bit(20+RECV_BITS);
do_left_shift_1bit(21+RECV_BITS);
do_left_shift_1bit(22+RECV_BITS);
}
}
if(Sync_Step=='C')
{
if((Sum_Max>Sum_FXMax)&&(Sum_Max>Sync21_Set))
{
Plc_Mode='R';
Sync_Step='F';
Sync_bit1_cnt=0;
plc_byte_data=0;
Work_step=1;
Plc_data_bit_cnt = 8;
//R_LED=1;
}
else
{
plc_restart_sync();
}
}
else
{
if((Sum_Max>Sum_FXMax)&&(Sum_Max>Sync21_Set))
{
Plc_SyncBZ=1;
Sync_Step='C';
T16G1IE=0;
}
else
{
plc_restart_sync();
}
}
}
void _Sync2_Proc(uchar offset)
{
uchar ucA,ucB,ucC;
Sum_Max=0;
Sum_FXMax=0; //0720
if (offset == 0) {
SYM_offset3=0;
SYCl_offset3=0;
}else {
SYM_offset4=0;
SYCl_offset4=0;
}
//BitData_T[23+offset]=BitData_T[0+offset];
for(ucB=0;ucB<8;ucB++) //约13335T
{
for(ucA=0;ucA<3;ucA++)
{
if (offset == 0) {
Sum_DM21_Sync3(ucA);
if(ZXDM>Sum_Max)
{
Sum_Max=ZXDM;
SYM_offset3=ucA;
SYCl_offset3=ucB;
}
}else{
Sum_DM21_Sync4(ucA);
if(ZXDM>Sum_Max)
{
Sum_Max=ZXDM;
SYM_offset4=ucA;
SYCl_offset4=ucB;
}
}
// else 6 nop
if(FXDM>Sum_FXMax)
{
Sum_FXMax=FXDM;
}
}
if (offset == 0)
{
do_left_shift_1bit_1(0);
do_left_shift_1bit_1(1);
do_left_shift_1bit_1(2);
do_left_shift_1bit_1(3);
do_left_shift_1bit_1(4);
do_left_shift_1bit_1(5);
do_left_shift_1bit_1(6);
do_left_shift_1bit_1(7);
do_left_shift_1bit_1(8);
do_left_shift_1bit_1(9);
do_left_shift_1bit_1(10);
do_left_shift_1bit_1(11);
do_left_shift_1bit_1(12);
do_left_shift_1bit_1(13);
do_left_shift_1bit_1(14);
do_left_shift_1bit_1(15);
do_left_shift_1bit_1(16);
do_left_shift_1bit_1(17);
do_left_shift_1bit_1(18);
do_left_shift_1bit_1(19);
do_left_shift_1bit_1(20);
do_left_shift_1bit_1(21);
do_left_shift_1bit_1(22);
//OFF_do(23);
}else{
do_left_shift_1bit_1(0+RECV_BITS);
do_left_shift_1bit_1(1+RECV_BITS);
do_left_shift_1bit_1(2+RECV_BITS);
do_left_shift_1bit_1(3+RECV_BITS);
do_left_shift_1bit_1(4+RECV_BITS);
do_left_shift_1bit_1(5+RECV_BITS);
do_left_shift_1bit_1(6+RECV_BITS);
do_left_shift_1bit_1(7+RECV_BITS);
do_left_shift_1bit_1(8+RECV_BITS);
do_left_shift_1bit_1(9+RECV_BITS);
do_left_shift_1bit_1(10+RECV_BITS);
do_left_shift_1bit_1(11+RECV_BITS);
do_left_shift_1bit_1(12+RECV_BITS);
do_left_shift_1bit_1(13+RECV_BITS);
do_left_shift_1bit_1(14+RECV_BITS);
do_left_shift_1bit_1(15+RECV_BITS);
do_left_shift_1bit_1(16+RECV_BITS);
do_left_shift_1bit_1(17+RECV_BITS);
do_left_shift_1bit_1(18+RECV_BITS);
do_left_shift_1bit_1(19+RECV_BITS);
do_left_shift_1bit_1(20+RECV_BITS);
do_left_shift_1bit_1(21+RECV_BITS);
do_left_shift_1bit_1(22+RECV_BITS);
}
}
if(Sync_Step=='D')
{
if((Sum_Max>Sum_FXMax)&&(Sum_Max>Sync21_Set))
{
Plc_Mode='R';
Sync_Step='E';
Sync_bit1_cnt=0;
plc_byte_data=0;
Work_step=1;
Plc_data_bit_cnt = 8;
//R_LED=1;
}
else
{
plc_restart_sync();
}
}
else
{
if((Sum_Max>Sum_FXMax)&&(Sum_Max>Sync21_Set))
{
Plc_SyncBZ=1;
Sync_Step='D';
T16G1IE=0;
}
else
{
plc_restart_sync();
}
}
}
//union SVR_INT_B08 t1, t2;
//int test;
/* sync_step C->F->D->E */
void Plc_SyncProc(void)
{
//T16G2IE = 0;
// t1.NumChar[0]=T16G1L;
// t1.NumChar[1] = T16G1H;
_Sync1_Proc(0);
if (Sync_Step == 'C')
_Sync1_Proc(1);
if (Sync_Step == 'F')
_Sync2_Proc(0);
if (Sync_Step == 'D')
_Sync2_Proc(1);
//t2.NumChar[0]=T16G1L;
// t2.NumChar[1] = T16G1H;
//test = t2.NumInt - t1.NumInt;
// T16G2IE = 1;
}
BOOL plc_tx_idle()
{
if (Plc_Mode != 0)//NOT IN TX and RX
return FALSE;
else
return TRUE;
}
int8u plc_tx_bytes(uchar *pdata ,uchar num)
{
if (FALSE == plc_tx_idle())
return 0;
plc_data[0]=0xaa;
plc_data[1]=num+2;
MMemcpy(&plc_data[2],pdata,num);
Ini_Plc_Tx();
S_LED=1;
R_LED = 0;
// cal_chk_sum();
Plc_Mode='T';
//tmr_init=0xff;
Work_step=0;
t_end_bit=0;
t_nor_bit=0;
Plc_data_bit_cnt=8;
Plc_data_byte_cnt=0;
Plc_data_len=num+2; //9
plc_byte_data=0xff;
Plc_Tx_first_Bit = 1;//first sync bit
Plc_Tx_Second_Bit = 1; // second sync bit
Plc_Tx_Third_Bit = 1;
Plc_Tx_Forth_Bit = 1;
//SSC15=Pn15_Con1;
IniT16G1(CCPMODE);
T16G2IE=0;
T16G2IF=0;
T16G1IF=0;
T16G1IE=1;
enable_irq();
// T16G1H=5;
// T16G1L=0;
return num;
}
int8u plc_rx_bytes(uchar *pdata)
{
if(Rx_status=='R')
{
int8u len = Plc_data_byte_cnt-1;
MMemcpy(pdata, &plc_data[1], len);
Plc_Mode=0;
IniT16G1(CCPMODE);
r_sync_bit=0;
Rx_status=0;
Plc_SyncBZ=0;
Sync_Step=0;
Plc_data_byte_cnt = 0;
T16G2IE=0;
T16G2IF=0;
Work_step=0;
//R_LED=0;
T16G1IF=0;
T16G1IE=1;
enable_irq();
S_LED=0;
return len;
}
return 0;
}
void plc_init(void)
{
PLC_RX;
T16G1R_S.NumLong=50000;
Ini_Plc_Rec();
PLC_RX;
watchdog();
PLC_RW=0x01;
PLC_ADDR=0x51;
testbyte=PLC_DATA;
PLC_RW=0x00;
r_sync_bit=0;
watchdog();
T16G2CH=0x0b;
T16G2CL=0x10; //4:1
IniT16G1(CCPMODE);
T16G1IF=0;
T16G1IE=1;
Plc_Mode = 0;
Plc_ZeroMode = 0;
Rec_Zero_bz= 0;
Plc_data_byte_cnt = 0;
}
void plc_driver_process(void)
{
watchdog();
if(Rec_Zero_bz)
{
if(Plc_Mode=='R')
{
if(Sync_Step=='E')
Plc_RecvProc();
}
else
{
if(Plc_Mode=='F')
{
Plc_SyncProc();
}
}
Rec_Zero_bz=0;
}
}
#endif /*ifdef CONFIG_400BPS_PLC*/
| C | CL | ef27f4aeeca36153e00fc277e2300cce32fd897eacd98af232c5abfa7c53fb35 |
/*
* Copyright 2007-2015 National ICT Australia (NICTA), Australia
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include <check.h>
#include "ocomm/o_log.h"
#include "oml_utils.h"
static struct uri_scheme {
char *uri;
OmlURIType expect;
} test_uri_schemes[] = {
{ "blah", OML_URI_UNKNOWN},
{ "file://blah", OML_URI_FILE },
{ "flush://blah", OML_URI_FILE_FLUSH },
{ "tcp://blah", OML_URI_TCP },
{ "udp://blah", OML_URI_UDP },
};
START_TEST (test_util_uri_scheme)
{
OmlURIType res;
res = oml_uri_type(test_uri_schemes[_i].uri);
fail_unless(
res == test_uri_schemes[_i].expect,
"Invalid type for `%s': %d instead of %d", test_uri_schemes[_i].uri, res, test_uri_schemes[_i].expect);
}
END_TEST
static struct uri {
char *uri;
int ret;
char *scheme;
char *host;
char *port;
char *path;
} test_uris[] = {
{ "localhost", 0, "tcp", "localhost", DEF_PORT_STRING, NULL},
{ "tcp://localhost", 0, "tcp", "localhost", DEF_PORT_STRING, NULL},
{ "tcp://localhost:3004", 0, "tcp", "localhost", "3004", NULL},
{ "localhost:3004", 0, "tcp", "localhost", "3004", NULL},
{ "127.0.0.1", 0, "tcp", "127.0.0.1", DEF_PORT_STRING, NULL},
{ "127.0.0.1:3004", 0, "tcp", "127.0.0.1", "3004", NULL},
{ "tcp://127.0.0.1", 0, "tcp", "127.0.0.1", DEF_PORT_STRING, NULL},
{ "tcp://127.0.0.1:3004", 0, "tcp", "127.0.0.1", "3004", NULL},
{ "[127.0.0.1]", 0, "tcp", "127.0.0.1", DEF_PORT_STRING, NULL},
{ "tcp://[127.0.0.1]", 0, "tcp", "127.0.0.1", DEF_PORT_STRING, NULL},
{ "tcp://[127.0.0.1]:3004", 0, "tcp", "127.0.0.1", "3004", NULL},
{ "[127.0.0.1]:3004", 0, "tcp", "127.0.0.1", "3004", NULL},
{ "[::1]", 0, "tcp", "::1", DEF_PORT_STRING, NULL},
{ "[::1]:3004", 0, "tcp", "::1", "3004", NULL},
{ "tcp://[::1]", 0, "tcp", "::1", DEF_PORT_STRING, NULL},
{ "tcp://[::1]:3004", 0, "tcp", "::1", "3004", NULL},
{ "file:-", 0, "file", NULL, NULL, "-"},
/* Backward compatibility */
{ "tcp:localhost:3004", 0, "tcp", "localhost", "3004", NULL},
{ "file:test_api_metadata", 0, "file", NULL, NULL, "test_api_metadata"},
{ "file://test_api_metadata", 0, "file", NULL, NULL, "//test_api_metadata"},
{ "file:///test_api_metadata", 0, "file", NULL, NULL, "///test_api_metadata"},
{ "::1", -1, NULL, NULL, NULL, NULL},
{ "::1:3003", -1, NULL, NULL, NULL, NULL},
{ "tcp:::1", -1, NULL, NULL, NULL, NULL},
{ "tcp:::1:3003", -1, NULL, NULL, NULL, NULL},
};
#define check_match(field) do { \
if (NULL == test_uris[_i].field) { \
fail_unless(test_uris[_i].field == NULL, "Unexpected " #field " from parse_uri(%s, %s, %s, %s, %s): %s instead of %s", \
test_uris[_i].uri, scheme, host, port, path, field, test_uris[_i].field); \
} else { \
fail_if(strcmp(field, test_uris[_i].field), "Unexpected " #field " from parse_uri(%s, %s, %s, %s, %s): %s instead of %s", \
test_uris[_i].uri, scheme, host, port, path, field, test_uris[_i].field); \
} \
} while(0)
START_TEST(test_util_parse_uri)
{
int ret;
const char *scheme, *host, *port, *path;
ret = parse_uri(test_uris[_i].uri, &scheme, &host, &port, &path);
fail_unless(test_uris[_i].ret == ret, "Unexpected status from parse_uri(%s, %s, %s, %s, %s): %d instead of %d",
test_uris[_i].uri, scheme, host, port, path, ret, test_uris[_i].ret);
check_match(scheme);
check_match(host);
check_match(port);
check_match(path);
}
END_TEST
Suite* util_suite (void)
{
Suite* s = suite_create ("oml_utils");
TCase* tc_util = tcase_create ("oml_utils");
tcase_add_loop_test (tc_util, test_util_uri_scheme, 0, LENGTH(test_uri_schemes));
tcase_add_loop_test (tc_util, test_util_parse_uri, 0, LENGTH(test_uris));
suite_add_tcase (s, tc_util);
return s;
}
/*
Local Variables:
mode: C
tab-width: 2
indent-tabs-mode: nil
End:
vim: sw=2:sts=2:expandtab
*/
| C | CL | bec785d27f7c5ebdc325dac6d618218048cf013b38cdd69e88bdd76044f74836 |
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (C) 2003-2008, Coolsand Technologies, Inc. //
// All Rights Reserved //
// //
// This source code is the property of Coolsand Technologies and is //
// confidential. Any modification, distribution, reproduction or //
// exploitation of any content of this file is totally forbidden, //
// except with the written permission of Coolsand Technologies. //
// //
////////////////////////////////////////////////////////////////////////////////
//
// $HeadURL: http://svn.coolsand-tech.com/svn/developing1/Sources/chip/branches/gallite441/boot/greenstone/src/boot_usb.c $
// $Author: admin $
// $Date: 2010-07-07 20:28:03 +0800 (Wed, 07 Jul 2010) $
// $Revision: 269 $
//
////////////////////////////////////////////////////////////////////////////////
//
/// @file boot_usb.c
///
/// Usb Function
//
////////////////////////////////////////////////////////////////////////////////
// =============================================================================
// HEADERS
// =============================================================================
#include "cs_types.h"
#include "global_macros.h"
#include "usbc.h"
#include "bootp_debug.h"
#include "boot_usb.h"
#include "hal_usb.h"
#include "hal_sys.h"
#include <string.h>
// =============================================================================
// MACROS
// =============================================================================
#define EPIN 0x01
#define EPOUT 0x02
#define EPINOUT 0x00
#define EPDIR(n) (((hwp_usbc->GHWCFG1)>>(2*n))&0x03)
#define SINGLE 0
#define INCR4 3
#define RXFIFOSIZE 64
#define TXFIFOSIZE 48
#ifndef USB_MAX_STRING
#define USB_MAX_STRING 8
#endif /* USB_MAX_STRING */
// =============================================================================
// TYPES
// =============================================================================
// =============================================================================
// BOOT_USB_REQUEST_DESTINATION_T
// -----------------------------------------------------------------------------
/// Destination of USB command
// =============================================================================
typedef enum
{
BOOT_USB_REQUEST_DESTINATION_DEVICE = 0,
BOOT_USB_REQUEST_DESTINATION_INTERFACE = 1,
BOOT_USB_REQUEST_DESTINATION_EP = 2
} BOOT_USB_REQUEST_DESTINATION_T ;
// =============================================================================
// BOOT_USB_REQUEST_DEVICE_T
// -----------------------------------------------------------------------------
/// List of device request
// =============================================================================
typedef enum
{
BOOT_USB_REQUEST_DEVICE_SETADDR = 0x05,
BOOT_USB_REQUEST_DEVICE_GETDESC = 0x06,
BOOT_USB_REQUEST_DEVICE_SETCONF = 0x09
} BOOT_USB_REQUEST_DEVICE_T ;
// =============================================================================
// BOOT_USB_REQUEST_EP_T
// -----------------------------------------------------------------------------
/// List of EndPoint request
// =============================================================================
typedef enum
{
BOOT_USB_REQUEST_EP_GET_STATUS = 0x00,
BOOT_USB_REQUEST_EP_CLEAR_FEATURE = 0x01,
BOOT_USB_REQUEST_EP_SET_FEATURE = 0x03
} BOOT_USB_REQUEST_EP_T ;
// =============================================================================
// BOOT_USB_DEVICE_DESCRIPTOR_REAL_T
// -----------------------------------------------------------------------------
/// Device descriptor structure
// =============================================================================
typedef struct
{
UINT8 size;
UINT8 type;
UINT16 bcdUsb;
UINT8 usbClass;
UINT8 usbSubClass;
UINT8 usbProto;
UINT8 ep0Mps;
UINT16 vendor;
UINT16 product;
UINT16 release;
UINT8 iManufacturer;
UINT8 iProduct;
UINT8 iSerial;
UINT8 nbConfig;
} PACKED BOOT_USB_DEVICE_DESCRIPTOR_REAL_T;
// =============================================================================
// BOOT_USB_CONFIG_DESCRIPTOR_REAL_T
// -----------------------------------------------------------------------------
/// Config descriptor structure
// =============================================================================
typedef struct
{
UINT8 size;
UINT8 type;
UINT16 totalLength;
UINT8 nbInterface;
UINT8 configIndex;
UINT8 iDescription;
UINT8 attrib;
UINT8 maxPower;
} PACKED BOOT_USB_CONFIG_DESCRIPTOR_REAL_T;
// =============================================================================
// BOOT_USB_INTERFACE_DESCRIPTOR_REAL_T
// -----------------------------------------------------------------------------
/// Interface descriptor structure
// =============================================================================
typedef struct
{
UINT8 size;
UINT8 type;
UINT8 interfaceIndex;
UINT8 alternateSetting;
UINT8 nbEp;
UINT8 usbClass;
UINT8 usbSubClass;
UINT8 usbProto;
UINT8 iDescription;
} PACKED BOOT_USB_INTERFACE_DESCRIPTOR_REAL_T;
// =============================================================================
// BOOT_USB_EP_DESCRIPTOR_REAL_T
// -----------------------------------------------------------------------------
/// Ep descriptor structure
// =============================================================================
typedef struct
{
UINT8 size;
UINT8 type;
UINT8 ep;
UINT8 attributes;
UINT16 mps;
UINT8 interval;
} PACKED BOOT_USB_EP_DESCRIPTOR_REAL_T;
// =============================================================================
// EP0_STATE_T
// -----------------------------------------------------------------------------
/// State of ep0
// =============================================================================
typedef enum
{
EP0_STATE_IDLE,
EP0_STATE_IN,
EP0_STATE_OUT,
EP0_STATE_STATUS_IN,
EP0_STATE_STATUS_OUT
} EP0_STATE_T ;
// =============================================================================
// BOOT_USB_TRANSFERT_T
// -----------------------------------------------------------------------------
/// Structure containt the transfert parameter
// =============================================================================
typedef struct
{
INT16 size;
} BOOT_USB_TRANSFERT_T;
// =============================================================================
// BOOT_USB_GLOBAL_VAR_T
// -----------------------------------------------------------------------------
/// Structure with all global var
// =============================================================================
typedef struct
{
HAL_USB_GETDESCRIPTOR_CALLBACK_T DeviceCallback;
HAL_USB_DEVICE_DESCRIPTOR_T* Desc;
HAL_USB_CALLBACK_T EpInCallback [DIEP_NUM];
HAL_USB_CALLBACK_T EpOutCallback[DOEP_NUM];
UINT32 EpFlag;
UINT8* String [USB_MAX_STRING];
// Transfert data
BOOT_USB_TRANSFERT_T InTransfert [DIEP_NUM+1];
BOOT_USB_TRANSFERT_T OutTransfert[DOEP_NUM+1];
// Ep0 State
HAL_USB_SETUP_REQUEST_DESC_T RequestDesc;
UINT8 Ep0State;
UINT8 Ep0Index;
UINT8 Config;
UINT8 NbEp;
UINT8 NbConfig;
UINT8 NbInterface;
UINT8 NbString;
} BOOT_USB_GLOBAL_VAR_T;
// =============================================================================
// PRIVATE VARIABLES
// =============================================================================
PRIVATE BOOT_USB_GLOBAL_VAR_T g_BootUsbVar;
// Ep0 Buffer
PRIVATE UINT8 ALIGNED(4) g_BootUsbBufferEp0Out[HAL_USB_MPS];
PRIVATE UINT8 ALIGNED(4) g_BootUsbBufferEp0In [HAL_USB_MPS];
PRIVATE CONST BOOT_USB_GLOBAL_VAR_T CONST *
__attribute__((section (".usbFixptr"),used))
g_BootUsbFixPtr = &g_BootUsbVar;
// =============================================================================
// GLOBAL VARIABLES
// =============================================================================
// =============================================================================
// PRIVATE FUNCTIONS PROTOTYPE
// =============================================================================
PRIVATE VOID boot_UsbConfigureEp(HAL_USB_EP_DESCRIPTOR_T* ep);
PRIVATE VOID boot_UsbDecodeEp0Packet(VOID);
PRIVATE VOID boot_getSetupPacket(VOID);
PRIVATE VOID boot_UsbEnableEp(UINT8 ep, HAL_USB_EP_TYPE_T type);
PRIVATE VOID boot_UsbDisableEp(UINT8 ep);
PRIVATE VOID boot_UsbClrConfig(VOID);
INLINE VOID boot_UsbStatusIn(VOID);
INLINE VOID boot_UsbStatusOut(VOID);
INLINE HAL_USB_CALLBACK_RETURN_T
boot_UsbCallbackEp(UINT8 ep,
HAL_USB_CALLBACK_EP_TYPE_T type,
HAL_USB_SETUP_T* setup);
INLINE HAL_USB_CALLBACK_RETURN_T
boot_UsbCallbackInterface(UINT8 ep,
HAL_USB_CALLBACK_EP_TYPE_T type,
HAL_USB_SETUP_T* setup);
PRIVATE UINT16 boot_generateDescConfig(HAL_USB_CONFIG_DESCRIPTOR_T* cfg,
UINT8* buffer,
UINT8 num);
PRIVATE UINT16
boot_generateDescEp(HAL_USB_EP_DESCRIPTOR_T* ep,
UINT8* buffer);
PRIVATE UINT16
boot_generateDescInterface(HAL_USB_INTERFACE_DESCRIPTOR_T* interface,
UINT8* buffer,
UINT8 num);
PRIVATE VOID boot_UsbCancelTransfert(UINT8 ep);
// =============================================================================
// boot_UsbFlushRxFifo
// -----------------------------------------------------------------------------
/// Flux reception USB fifo
// =============================================================================
PRIVATE VOID boot_UsbFlushRxFifo(VOID);
// =============================================================================
// boot_UsbFlushTxFifo
// -----------------------------------------------------------------------------
/// Flush transmition USB FIFO
/// @param ep Define the endpoint index for the direction
/// use #HAL_USB_EP_DIRECTION_IN and use #HAL_USB_EP_DIRECTION_OUT
// =============================================================================
PRIVATE VOID boot_UsbFlushTxFifo(UINT8 ep);
// =============================================================================
// boot_UsbFlushAllTxFifos
// -----------------------------------------------------------------------------
/// Flush all transmition USB FIFOS
// =============================================================================
PRIVATE VOID boot_UsbFlushAllTxFifos(VOID);
// =============================================================================
// boot_usbAsciiToUtf8
// -----------------------------------------------------------------------------
/// Convert string to utf8
/// @param utf8 destination string
/// @param acsii source string
// =============================================================================
PRIVATE VOID boot_usbAsciiToUtf8(UINT8 *utf8, UINT8 *acsii);
// =============================================================================
// PRIVATE FUNCTION
// =============================================================================
PRIVATE VOID boot_usbAsciiToUtf8(UINT8 *utf8, UINT8 *acsii)
{
while(*acsii)
{
*utf8 = *acsii;
utf8++;
*utf8 = 0;
utf8++;
acsii++;
}
}
PRIVATE VOID boot_UsbFlushRxFifo(VOID)
{
hwp_usbc->GRSTCTL |= USBC_RXFFLSH;
}
PRIVATE VOID boot_UsbFlushTxFifo(UINT8 ep)
{
UINT8 epNum;
epNum = HAL_USB_EP_NUM(ep);
hwp_usbc->GRSTCTL &= ~USBC_TXFNUM_MASK;
hwp_usbc->GRSTCTL |= USBC_TXFNUM(epNum);
hwp_usbc->GRSTCTL |= USBC_TXFFLSH;
}
PRIVATE VOID boot_UsbFlushAllTxFifos(VOID)
{
hwp_usbc->GRSTCTL &= ~USBC_TXFNUM_MASK;
hwp_usbc->GRSTCTL |= USBC_TXFNUM(0x10);
hwp_usbc->GRSTCTL |= USBC_TXFFLSH;
}
PRIVATE VOID boot_UsbResetTransfert(VOID)
{
UINT8 i;
for(i = 0; i < DIEP_NUM+1; ++i)
{
g_BootUsbVar.InTransfert[i].size = 0;
}
for(i = 0; i < DOEP_NUM+1; ++i)
{
g_BootUsbVar.OutTransfert[i].size = 0;
}
}
PRIVATE UINT8 boot_UsbStartTransfert(UINT8 ep, VOID *data, UINT16 size,
UINT32 flag)
{
UINT8 epNum;
UINT16 nbPacket;
REG32* regDma;
REG32* regSize;
REG32* regCtl;
epNum = HAL_USB_EP_NUM(ep);
if(HAL_USB_IS_EP_DIRECTION_IN(ep))
{
if(g_BootUsbVar.InTransfert[epNum].size > 0)
{
return(1);
}
if(epNum == 0)
{
regDma = &hwp_usbc->DIEPDMA0;
regSize = &hwp_usbc->DIEPTSIZ0;
regCtl = &hwp_usbc->DIEPCTL0;
}
else
{
regDma = &hwp_usbc->DIEPnCONFIG[epNum-1].DIEPDMA;
regSize = &hwp_usbc->DIEPnCONFIG[epNum-1].DIEPTSIZ;
regCtl = &hwp_usbc->DIEPnCONFIG[epNum-1].DIEPCTL;
}
g_BootUsbVar.EpFlag &= ~(1<<epNum);
if(flag)
{
g_BootUsbVar.EpFlag |= 1<<epNum;
}
if(size < HAL_USB_MPS)
{
*regSize = USBC_IEPXFERSIZE(size) | USBC_IEPPKTCNT(1);
}
else
{
nbPacket = size/HAL_USB_MPS;
*regSize = USBC_IEPXFERSIZE(nbPacket*HAL_USB_MPS) |
USBC_IEPPKTCNT(nbPacket);
}
g_BootUsbVar.InTransfert[epNum].size = size;
}
// Out
else
{
if(g_BootUsbVar.OutTransfert[epNum].size > 0)
{
return(1);
}
g_BootUsbVar.OutTransfert[epNum].size = size;
if(epNum == 0)
{
regDma = &hwp_usbc->DOEPDMA0;
regSize = &hwp_usbc->DOEPTSIZ0;
regCtl = &hwp_usbc->DOEPCTL0;
}
else
{
regDma = &hwp_usbc->DOEPnCONFIG[epNum-1].DOEPDMA;
regSize = &hwp_usbc->DOEPnCONFIG[epNum-1].DOEPTSIZ;
regCtl = &hwp_usbc->DOEPnCONFIG[epNum-1].DOEPCTL;
}
*regSize = USBC_OEPXFERSIZE(size) | USBC_OEPPKTCNT(size/HAL_USB_MPS);
}
*regDma = (REG32) data;
*regCtl |= USBC_EPENA | USBC_CNAK;
return(0);
}
PRIVATE VOID boot_UsbCancelTransfert(UINT8 ep)
{
UINT8 epNum;
epNum = HAL_USB_EP_NUM(ep);
if(HAL_USB_IS_EP_DIRECTION_IN(ep))
{
g_BootUsbVar.InTransfert[epNum].size = 0;
}
else
{
g_BootUsbVar.OutTransfert[epNum].size = 0;
}
}
PRIVATE UINT8 boot_UsbContinueTransfert(UINT8 ep)
{
UINT8 epNum;
REG32* regSize;
REG32* regCtl;
epNum = HAL_USB_EP_NUM(ep);
if(HAL_USB_IS_EP_DIRECTION_IN(ep))
{
if(g_BootUsbVar.InTransfert[epNum].size <= 0)
{
return(1);
}
if(!(g_BootUsbVar.EpFlag & (1<<epNum)))
{
if(g_BootUsbVar.InTransfert[epNum].size >= HAL_USB_MPS)
{
if(epNum == 0)
{
regSize = &hwp_usbc->DIEPTSIZ0;
regCtl = &hwp_usbc->DIEPCTL0;
}
else
{
regSize = &hwp_usbc->DIEPnCONFIG[epNum-1].DIEPTSIZ;
regCtl = &hwp_usbc->DIEPnCONFIG[epNum-1].DIEPCTL;
}
*regSize = USBC_IEPXFERSIZE(g_BootUsbVar.InTransfert[epNum].size
% HAL_USB_MPS) | USBC_IEPPKTCNT(1);
*regCtl |= USBC_EPENA | USBC_CNAK;
g_BootUsbVar.InTransfert[epNum].size = 1;
return(0);
}
}
g_BootUsbVar.InTransfert[epNum].size = 0;
}
else
{
if(g_BootUsbVar.OutTransfert[epNum].size <= 0)
{
return(1);
}
if(epNum == 0)
{
regSize = &hwp_usbc->DOEPTSIZ0;
}
else
{
regSize = &hwp_usbc->DOEPnCONFIG[epNum-1].DOEPTSIZ;
}
g_BootUsbVar.OutTransfert[epNum].size -=
GET_BITFIELD(*regSize, USBC_OEPXFERSIZE);
g_BootUsbVar.OutTransfert[epNum].size =
-g_BootUsbVar.OutTransfert[epNum].size;
if(g_BootUsbVar.OutTransfert[epNum].size > 0)
{
g_BootUsbVar.OutTransfert[epNum].size = 0;
}
}
return(1);
}
PRIVATE VOID boot_UsbConfigureEp(HAL_USB_EP_DESCRIPTOR_T* ep)
{
UINT8 epNum;
epNum = HAL_USB_EP_NUM(ep->ep);
if(HAL_USB_IS_EP_DIRECTION_IN(ep->ep))
{
g_BootUsbVar.EpInCallback[epNum-1] = ep->callback;
boot_UsbEnableEp(HAL_USB_EP_DIRECTION_IN(epNum), ep->type);
}
else
{
g_BootUsbVar.EpOutCallback[epNum-1] = ep->callback;
boot_UsbEnableEp(HAL_USB_EP_DIRECTION_OUT(epNum), ep->type);
}
}
PRIVATE VOID boot_UsbInit(VOID)
{
// Flush fifo
boot_UsbFlushAllTxFifos();
boot_UsbFlushRxFifo();
// Reset EP0 state
g_BootUsbVar.Ep0State = EP0_STATE_IDLE;
g_BootUsbVar.NbString = 0;
boot_UsbClrConfig();
g_BootUsbVar.Desc = 0;
boot_UsbResetTransfert();
}
PRIVATE VOID boot_UsbConfig(VOID)
{
UINT8 i;
UINT16 addr;
UINT8 dir;
// Nb EP
g_BootUsbVar.NbEp = GET_BITFIELD(hwp_usbc->GHWCFG2, USBC_NUMDEVEPS);
g_BootUsbVar.NbEp++;
// Rx Fifo Size
hwp_usbc->GRXFSIZ = RXFIFOSIZE;
addr = RXFIFOSIZE;
// EP direction and Tx fifo configuration
hwp_usbc->GNPTXFSIZ = USBC_NPTXFSTADDR(addr) | USBC_NPTXFDEPS(TXFIFOSIZE);
addr += TXFIFOSIZE;
for(i = 1; i < g_BootUsbVar.NbEp; i++)
{
dir = EPDIR(i);
if(dir == EPIN || dir == EPINOUT)
{
hwp_usbc->DIEPTXF[i-1].DIEnPTXF =
USBC_IENPNTXFSTADDR(addr) | USBC_INEPNTXFDEP(TXFIFOSIZE);
addr += TXFIFOSIZE;
}
}
hwp_usbc->GAHBCFG = USBC_DMAEN | USBC_HBSTLEN(INCR4);
hwp_usbc->GAHBCFG |= USBC_GLBLINTRMSK;
hwp_usbc->GUSBCFG |= USBC_PHYIF | USBC_USBTRDTIM(5);
hwp_usbc->DCFG &= ~(USBC_DEVSPD_MASK | USBC_PERFRINT_MASK);
// Configure FS USB 1.1 Phy
hwp_usbc->DCFG |= USBC_DEVSPD(3);
hwp_usbc->GINTMSK |= USBC_USBRST | USBC_ENUMDONE
| USBC_ERLYSUSP | USBC_USBSUSP;
}
PRIVATE VOID boot_UsbDisableEp(UINT8 ep)
{
UINT8 epNum;
UINT8 offset;
REG32* diepctl;
REG32* doepctl;
REG32* ctl;
epNum = HAL_USB_EP_NUM(ep);
// Select ctl register
if(epNum == 0)
{
diepctl = &hwp_usbc->DIEPCTL0;
doepctl = &hwp_usbc->DOEPCTL0;
}
else
{
diepctl = &hwp_usbc->DIEPnCONFIG[epNum-1].DIEPCTL;
doepctl = &hwp_usbc->DOEPnCONFIG[epNum-1].DOEPCTL;
}
// Select direction
if(HAL_USB_IS_EP_DIRECTION_IN(ep))
{
offset = 0;
ctl = diepctl;
}
else
{
offset = 16;
ctl = doepctl;
}
if(*ctl & USBC_EPENA)
{
*ctl = USBC_EPDIS | USBC_SNAK;
}
else
{
*ctl = USBC_SNAK;
}
boot_UsbFlushTxFifo(epNum);
boot_UsbCancelTransfert(ep);
hwp_usbc->DAINT &= ~(1<<(epNum+offset));
}
PRIVATE VOID boot_UsbEnableEp(UINT8 ep, HAL_USB_EP_TYPE_T type)
{
UINT8 epNum;
UINT8 offset;
REG32* diepctl;
REG32* doepctl;
REG32* ctl;
epNum = HAL_USB_EP_NUM(ep);
// Select ctl register
if(epNum == 0)
{
diepctl = &hwp_usbc->DIEPCTL0;
doepctl = &hwp_usbc->DOEPCTL0;
}
else
{
diepctl = &hwp_usbc->DIEPnCONFIG[epNum-1].DIEPCTL;
doepctl = &hwp_usbc->DOEPnCONFIG[epNum-1].DOEPCTL;
}
// Select direction
if(HAL_USB_IS_EP_DIRECTION_IN(ep))
{
offset = 0;
ctl = diepctl;
}
else
{
offset = 16;
ctl = doepctl;
}
/* if(*ctl & USBC_USBACTEP) */
/* { */
if(type == HAL_USB_EP_TYPE_ISO)
{
*ctl = USBC_EPN_MPS(HAL_USB_MPS) | USBC_EPTYPE(type) | USBC_USBACTEP
| USBC_EPTXFNUM(epNum) | USBC_NEXTEP(epNum);
}
else
{
*ctl = USBC_EPN_MPS(HAL_USB_MPS) | USBC_EPTYPE(type) | USBC_USBACTEP
| USBC_EPTXFNUM(epNum) | USBC_SETD0PID | USBC_NEXTEP(epNum);
}
/* } */
hwp_usbc->DAINTMSK |= (1<<(epNum+offset));
}
INLINE UINT8 boot_UsbAddString(UINT8 *str)
{
UINT8 i;
if(str == 0)
{
return(0);
}
for(i = 0; i < g_BootUsbVar.NbString; ++i)
{
if(g_BootUsbVar.String[i] == str)
{
return(i);
}
}
g_BootUsbVar.String[g_BootUsbVar.NbString] = str;
g_BootUsbVar.NbString++;
return(g_BootUsbVar.NbString);
}
PRIVATE VOID boot_generateDescDevice(HAL_USB_DEVICE_DESCRIPTOR_T* dev,
UINT8* buffer)
{
BOOT_USB_DEVICE_DESCRIPTOR_REAL_T* desc;
UINT8 i;
g_BootUsbVar.NbConfig = 0;
desc = (BOOT_USB_DEVICE_DESCRIPTOR_REAL_T*) buffer;
desc->size = sizeof(BOOT_USB_DEVICE_DESCRIPTOR_REAL_T);
// Device type = 1
desc->type = 1;
desc->bcdUsb = 0x0110;
desc->usbClass = dev->usbClass;
desc->usbSubClass = dev->usbSubClass;
desc->usbProto = dev->usbProto;
desc->ep0Mps = HAL_USB_MPS;
desc->vendor = dev->vendor;
desc->product = dev->product;
desc->release = 0x0001;
desc->iManufacturer = boot_UsbAddString("Coolsand Technologies");
desc->iProduct = boot_UsbAddString(dev->description);
desc->iSerial = boot_UsbAddString(dev->serialNumber);
i = 0;
if(dev->configList)
{
for(i = 0; dev->configList[i]; ++i);
}
desc->nbConfig = i;
g_BootUsbVar.NbConfig = i;
}
PRIVATE UINT16 boot_generateDescConfig(HAL_USB_CONFIG_DESCRIPTOR_T* cfg,
UINT8* buffer,
UINT8 num)
{
BOOT_USB_CONFIG_DESCRIPTOR_REAL_T* desc;
UINT16 size;
UINT8 i;
desc = (BOOT_USB_CONFIG_DESCRIPTOR_REAL_T*) buffer;
desc->size = sizeof(BOOT_USB_CONFIG_DESCRIPTOR_REAL_T);
size = sizeof(BOOT_USB_CONFIG_DESCRIPTOR_REAL_T);
// Config type = 2
desc->type = 2;
i = 0;
if(cfg->interfaceList)
{
for(i = 0; cfg->interfaceList[i]; ++i)
{
size += boot_generateDescInterface(cfg->interfaceList[i],
&buffer[size], i);
}
}
desc->nbInterface = i;
desc->configIndex = num;
desc->iDescription = boot_UsbAddString(cfg->description);
desc->attrib = cfg->attrib;
desc->maxPower = cfg->maxPower;
desc->totalLength = size;
return(size);
}
PRIVATE UINT16
boot_generateDescInterface(HAL_USB_INTERFACE_DESCRIPTOR_T* interface,
UINT8* buffer,
UINT8 num)
{
UINT8 i;
BOOT_USB_INTERFACE_DESCRIPTOR_REAL_T* desc;
UINT16 size;
desc = (BOOT_USB_INTERFACE_DESCRIPTOR_REAL_T*) buffer;
desc->size = sizeof(BOOT_USB_INTERFACE_DESCRIPTOR_REAL_T);
size = sizeof(BOOT_USB_INTERFACE_DESCRIPTOR_REAL_T);
// Interface type = 4
desc->type = 4;
desc->interfaceIndex = num;
desc->alternateSetting = 0;
i = 0;
if(interface->epList)
{
for(i = 0; interface->epList[i]; ++i)
{
size += boot_generateDescEp(interface->epList[i],
&buffer[size]);
}
}
desc->nbEp = i;
desc->usbClass = interface->usbClass ;
desc->usbSubClass = interface->usbSubClass;
desc->usbProto = interface->usbProto ;
desc->iDescription = boot_UsbAddString(interface->description);
return(size);
}
PRIVATE UINT16
boot_generateDescEp(HAL_USB_EP_DESCRIPTOR_T* ep,
UINT8* buffer)
{
BOOT_USB_EP_DESCRIPTOR_REAL_T* desc;
desc = (BOOT_USB_EP_DESCRIPTOR_REAL_T*) buffer;
desc->size = sizeof(BOOT_USB_EP_DESCRIPTOR_REAL_T);
// EP type = 4
desc->type = 5;
desc->ep = ep->ep;
// EP Type (Cmd, Bulk, Iso, Int)
desc->attributes = ep->type;
desc->mps = HAL_USB_MPS;
desc->interval = ep->interval;
return(desc->size);
}
PRIVATE VOID boot_getSetupPacket(VOID)
{
hwp_usbc->DOEPTSIZ0 = USBC_SUPCNT(1) |
USBC_OEPXFERSIZE0(8) | USBC_OEPPKTCNT0;
hwp_usbc->DOEPDMA0 = (UINT32) g_BootUsbBufferEp0Out;
hwp_usbc->DOEPCTL0 |= USBC_CNAK | USBC_EPENA;
}
INLINE VOID boot_UsbStatusIn(VOID)
{
g_BootUsbVar.Ep0State = EP0_STATE_STATUS_IN;
boot_UsbSend(0, g_BootUsbBufferEp0In, 0, 0);
boot_getSetupPacket();
}
INLINE VOID boot_UsbStatusOut(VOID)
{
/* hwp_usbc->DCFG |= USBC_NZSTSOUTHSHK; */
g_BootUsbVar.Ep0State = EP0_STATE_STATUS_OUT;
boot_UsbRecv(0, g_BootUsbBufferEp0Out, 0, 0);
}
PRIVATE VOID boot_UsbClrConfig(VOID)
{
UINT8 i;
if(g_BootUsbVar.Config != 0xFF)
{
for(i = 0;
g_BootUsbVar.Desc->configList[g_BootUsbVar.Config]
->interfaceList[i];
++i)
{
if(g_BootUsbVar.Desc->configList[g_BootUsbVar.Config]
->interfaceList[i]->callback)
{
g_BootUsbVar.Desc->configList[g_BootUsbVar.Config]
->interfaceList[i]->callback
(HAL_USB_CALLBACK_TYPE_DISABLE, 0);
}
}
}
g_BootUsbVar.Config = 0xFF;
/* Disable all EP */
for(i = 0; i < DIEP_NUM; ++i)
{
g_BootUsbVar.EpInCallback[i] = 0;
boot_UsbDisableEp(HAL_USB_EP_DIRECTION_IN (i+1));
}
for(i = 0; i < DOEP_NUM; ++i)
{
g_BootUsbVar.EpOutCallback[i] = 0;
boot_UsbDisableEp(HAL_USB_EP_DIRECTION_OUT(i+1));
}
}
INLINE HAL_USB_CALLBACK_RETURN_T
boot_UsbCallbackEp(UINT8 ep,
HAL_USB_CALLBACK_EP_TYPE_T type,
HAL_USB_SETUP_T* setup)
{
UINT8 epNum;
epNum = HAL_USB_EP_NUM(ep);
if(epNum < 16 &&
epNum != 0)
{
if(HAL_USB_IS_EP_DIRECTION_IN(ep))
{
if(g_BootUsbVar.EpInCallback[epNum-1])
{
return(g_BootUsbVar.EpInCallback[epNum-1](type, setup));
}
}
else
{
if(g_BootUsbVar.EpOutCallback[epNum-1])
{
return(g_BootUsbVar.EpOutCallback[epNum-1](type, setup));
}
}
}
return(HAL_USB_CALLBACK_RETURN_KO);
}
INLINE HAL_USB_CALLBACK_RETURN_T
boot_UsbCallbackInterface(UINT8 interface,
HAL_USB_CALLBACK_EP_TYPE_T type,
HAL_USB_SETUP_T* setup)
{
if(g_BootUsbVar.Desc == 0)
{
return(HAL_USB_CALLBACK_RETURN_KO);
}
if(g_BootUsbVar.Config >= g_BootUsbVar.NbConfig)
{
return(HAL_USB_CALLBACK_RETURN_KO);
}
if(g_BootUsbVar.Desc->configList[g_BootUsbVar.Config] == 0)
{
return(HAL_USB_CALLBACK_RETURN_KO);
}
if(interface >= g_BootUsbVar.NbInterface)
{
return(HAL_USB_CALLBACK_RETURN_KO);
}
if(g_BootUsbVar.Desc->configList[g_BootUsbVar.Config]->
interfaceList[interface]->callback == 0)
{
return(HAL_USB_CALLBACK_RETURN_KO);
}
return(g_BootUsbVar.Desc->configList[g_BootUsbVar.Config]->
interfaceList[interface]->
callback(type, setup));
}
PRIVATE VOID boot_UsbSetConfig(UINT8 num)
{
UINT8 i;
UINT8 j;
// Disable old config
boot_UsbClrConfig();
g_BootUsbVar.Config = num;
for(i = 0; g_BootUsbVar.Desc->configList[num]->interfaceList[i]; ++i)
{
for(j = 0;
g_BootUsbVar.Desc->configList[num]->interfaceList[i]->epList[j];
++j)
{
boot_UsbConfigureEp(g_BootUsbVar.Desc->configList[num]->
interfaceList[i]->epList[j]);
}
if(g_BootUsbVar.Desc->configList[num]->interfaceList[i]->callback)
{
g_BootUsbVar.Desc->configList[num]->
interfaceList[i]->callback(HAL_USB_CALLBACK_TYPE_ENABLE, 0);
}
}
g_BootUsbVar.NbInterface = i;
}
PRIVATE VOID boot_UsbDecodeEp0Packet(VOID)
{
HAL_USB_SETUP_T* setup = NULL;
UINT16 size;
UINT8 setup_completed = 0;
switch(g_BootUsbVar.Ep0State)
{
case EP0_STATE_IDLE :
setup =
(HAL_USB_SETUP_T*) HAL_SYS_GET_UNCACHED_ADDR(g_BootUsbBufferEp0Out);
// Change endian less
setup->value = HAL_ENDIAN_LITTLE_16(setup->value );
setup->index = HAL_ENDIAN_LITTLE_16(setup->index );
setup->lenght = HAL_ENDIAN_LITTLE_16(setup->lenght);
g_BootUsbVar.RequestDesc = setup->requestDesc;
g_BootUsbVar.Ep0Index = setup->index&0xff;
if(setup->lenght == 0)
{
if(setup->requestDesc.requestDirection)
{
g_BootUsbVar.Ep0State = EP0_STATE_STATUS_OUT;
}
else
{
g_BootUsbVar.Ep0State = EP0_STATE_STATUS_IN;
}
}
else
{
if(setup->requestDesc.requestDirection)
{
g_BootUsbVar.Ep0State = EP0_STATE_IN;
}
else
{
g_BootUsbVar.Ep0State = EP0_STATE_OUT;
}
}
switch(setup->requestDesc.requestDest)
{
case BOOT_USB_REQUEST_DESTINATION_DEVICE:
switch(setup->request)
{
case BOOT_USB_REQUEST_DEVICE_SETADDR:
hwp_usbc->DCFG |= USBC_DEVADDR(setup->value);
setup_completed = 1;
break;
case BOOT_USB_REQUEST_DEVICE_SETCONF:
if(g_BootUsbVar.Desc == 0)
{
break;
}
if((setup->value&0xFF) <= g_BootUsbVar.NbConfig)
{
setup_completed = 1;
boot_UsbSetConfig((setup->value&0xFF)-1);
}
break;
case BOOT_USB_REQUEST_DEVICE_GETDESC:
if(g_BootUsbVar.Desc == 0)
{
break;
}
size = 0;
switch(setup->value>>8)
{
case 1: /* Device */
boot_generateDescDevice(g_BootUsbVar.Desc,
g_BootUsbBufferEp0In);
size = sizeof(BOOT_USB_DEVICE_DESCRIPTOR_REAL_T);
break;
case 2: /* Config */
size = boot_generateDescConfig(
g_BootUsbVar.Desc->configList[(setup->value&0xFF)],
g_BootUsbBufferEp0In, (setup->value&0xFF)+1);
break;
case 3: /* String */
if((setup->value&0xFF) == 0)
{
size = 0x04;
g_BootUsbBufferEp0In[0] = 0x04;
g_BootUsbBufferEp0In[1] = 0x03;
g_BootUsbBufferEp0In[2] = 0x09;
g_BootUsbBufferEp0In[3] = 0x04;
}
else
{
size = 0;
if((setup->value&0xFF) <= g_BootUsbVar.NbString)
{
size =
strlen(g_BootUsbVar.String[(setup->value&0xFF)-1])*2
+ 2;
g_BootUsbBufferEp0In[0] = size;
g_BootUsbBufferEp0In[1] = 0x03;
boot_usbAsciiToUtf8(&g_BootUsbBufferEp0In[2],
g_BootUsbVar.String
[(setup->value&0xFF)-1]);
}
}
break;
}
if(setup->lenght < size)
{
size = setup->lenght;
}
/* Data in */
boot_UsbSend(0, g_BootUsbBufferEp0In, size, 0);
setup_completed = 1;
break;
}
break;
case BOOT_USB_REQUEST_DESTINATION_INTERFACE:
switch(boot_UsbCallbackInterface(setup->index&0xFF,
HAL_USB_CALLBACK_TYPE_CMD, setup))
{
case HAL_USB_CALLBACK_RETURN_OK:
setup_completed = 1;
break;
case HAL_USB_CALLBACK_RETURN_RUNNING:
setup_completed = 2;
break;
case HAL_USB_CALLBACK_RETURN_KO:
break;
}
break;
case BOOT_USB_REQUEST_DESTINATION_EP:
switch(setup->request)
{
case BOOT_USB_REQUEST_EP_GET_STATUS :
break;
case BOOT_USB_REQUEST_EP_CLEAR_FEATURE:
if(setup->value == 0 || setup->value & 0x01)
{
boot_UsbEpStall(setup->index&0xFF, FALSE);
}
setup_completed = 1;
break;
case BOOT_USB_REQUEST_EP_SET_FEATURE :
break;
default:
break;
}
switch(boot_UsbCallbackEp(setup->index&0xFF,
HAL_USB_CALLBACK_TYPE_CMD, setup))
{
case HAL_USB_CALLBACK_RETURN_OK:
setup_completed = 1;
break;
case HAL_USB_CALLBACK_RETURN_RUNNING:
setup_completed = 2;
break;
case HAL_USB_CALLBACK_RETURN_KO:
break;
}
break;
default:
break;
}
if(setup_completed == 0 || setup_completed == 1)
{
if(setup->lenght == 0)
{
if(setup->requestDesc.requestDirection)
{
boot_UsbStatusOut();
}
else
{
boot_UsbStatusIn();
}
}
}
if(setup_completed == 0)
{
if(setup->lenght != 0)
{
if(setup->requestDesc.requestDirection)
{
boot_UsbSend(0, g_BootUsbBufferEp0In, 0, 0);
}
else
{
boot_UsbRecv(0, g_BootUsbBufferEp0Out, HAL_USB_MPS, 0);
}
}
}
break;
case EP0_STATE_IN :
/* Transfert finish */
if(boot_UsbContinueTransfert(HAL_USB_EP_DIRECTION_IN(0)))
{
switch(g_BootUsbVar.RequestDesc.requestDest)
{
case BOOT_USB_REQUEST_DESTINATION_DEVICE:
break;
case BOOT_USB_REQUEST_DESTINATION_INTERFACE:
boot_UsbCallbackInterface(g_BootUsbVar.Ep0Index&0xFF,
HAL_USB_CALLBACK_TYPE_DATA_CMD,
setup);
break;
case BOOT_USB_REQUEST_DESTINATION_EP:
boot_UsbCallbackEp(setup->index&0xFF,
HAL_USB_CALLBACK_TYPE_CMD, setup);
break;
}
boot_UsbStatusOut();
}
break;
case EP0_STATE_OUT :
/* Transfert finish */
if(boot_UsbContinueTransfert(HAL_USB_EP_DIRECTION_OUT(0)))
{
switch(g_BootUsbVar.RequestDesc.requestDest)
{
case BOOT_USB_REQUEST_DESTINATION_DEVICE:
break;
case BOOT_USB_REQUEST_DESTINATION_INTERFACE:
boot_UsbCallbackInterface(g_BootUsbVar.Ep0Index&0xFF,
HAL_USB_CALLBACK_TYPE_DATA_CMD,
setup);
break;
case BOOT_USB_REQUEST_DESTINATION_EP:
boot_UsbCallbackEp(setup->index&0xFF,
HAL_USB_CALLBACK_TYPE_CMD, setup);
break;
}
boot_UsbStatusIn();
}
break;
case EP0_STATE_STATUS_IN:
boot_UsbContinueTransfert(HAL_USB_EP_DIRECTION_IN(0));
g_BootUsbVar.Ep0State = EP0_STATE_IDLE;
boot_getSetupPacket();
break;
case EP0_STATE_STATUS_OUT:
boot_UsbContinueTransfert(HAL_USB_EP_DIRECTION_OUT(0));
g_BootUsbVar.Ep0State = EP0_STATE_IDLE;
boot_getSetupPacket();
break;
}
}
// =============================================================================
// FUNCTIONS
// =============================================================================
PUBLIC VOID boot_UsbInitVar(VOID)
{
g_BootUsbVar.DeviceCallback = 0;
g_BootUsbVar.Desc = 0;
g_BootUsbVar.NbEp = 0;
g_BootUsbVar.NbConfig = 0;
g_BootUsbVar.NbInterface = 0;
g_BootUsbVar.NbString = 0;
g_BootUsbVar.Ep0State = EP0_STATE_IDLE;
g_BootUsbVar.Config = 0xFF;
}
PUBLIC VOID boot_UsbIrqHandler(UINT8 interruptId)
{
UINT32 status;
UINT32 statusEp;
UINT32 data;
UINT8 i;
// To keep the compiler warning (unused variable)
interruptId = interruptId;
BOOT_PROFILE_FUNCTION_ENTER(boot_UsbIrqHandler);
status = hwp_usbc->GINTSTS;
hwp_usbc->GINTSTS |= status;
if(status & USBC_USBRST)
{
BOOT_PROFILE_FUNCTION_ENTER(boot_UsbIrqHandlerReset);
boot_UsbInit();
// Get usb description
if(g_BootUsbVar.DeviceCallback != 0)
{
g_BootUsbVar.Desc = g_BootUsbVar.DeviceCallback();
}
hwp_usbc->DCFG = USBC_DEVSPD(3);
// Enable DMA INCR4
hwp_usbc->GINTMSK |= USBC_OEPINT | USBC_IEPINT;
hwp_usbc->GAHBCFG |= USBC_DMAEN | USBC_HBSTLEN(INCR4);
// EP interrupt EP0 IN/OUT
hwp_usbc->DAINTMSK = 1 | (1<<16);
hwp_usbc->DOEPMSK = USBC_SETUPMK | USBC_XFERCOMPLMSK;
hwp_usbc->DIEPMSK = USBC_TIMEOUTMSK | USBC_XFERCOMPLMSK;
// Config EP0
boot_getSetupPacket();
BOOT_PROFILE_FUNCTION_EXIT(boot_UsbIrqHandlerReset);
}
if(status & USBC_ENUMDONE)
{
BOOT_PROFILE_FUNCTION_ENTER(boot_UsbIrqHandlerEnum);
// Config max packet size
hwp_usbc->DIEPCTL0 = USBC_EP0_MPS(0);
hwp_usbc->DOEPCTL0 = USBC_EP0_MPS(0);
hwp_usbc->DOEPCTL0 |= USBC_EPENA | USBC_CNAK;
BOOT_PROFILE_FUNCTION_EXIT(boot_UsbIrqHandlerEnum);
}
if(status & USBC_IEPINT) // TX
{
BOOT_PROFILE_FUNCTION_ENTER(boot_UsbIrqHandlerI);
data = hwp_usbc->DAINT;
for(i = 0; i < g_BootUsbVar.NbEp; ++i)
{
if((data>>i)&1)
{
if(i == 0)
{
statusEp = hwp_usbc->DIEPINT0;
if(statusEp & USBC_TIMEOUTMSK)
{
BOOT_PROFILE_FUNCTION_ENTER(boot_UsbIrqHandlerIto);
// Clear Timeout interupt
hwp_usbc->DIEPINT0 = USBC_SETUPMK;
BOOT_PROFILE_FUNCTION_EXIT(boot_UsbIrqHandlerIto);
}
if(statusEp & USBC_XFERCOMPLMSK)
{
BOOT_PROFILE_FUNCTION_ENTER(boot_UsbIrqHandlerIcp);
// Clear transfert completed interrupt
hwp_usbc->DIEPINT0 = USBC_XFERCOMPLMSK;
// Decode Ep0 command
boot_UsbDecodeEp0Packet();
BOOT_PROFILE_FUNCTION_EXIT(boot_UsbIrqHandlerIcp);
}
}
else
{
statusEp = hwp_usbc->DIEPnCONFIG[i-1].DIEPINT;
hwp_usbc->DIEPnCONFIG[i-1].DIEPINT = statusEp;
if(statusEp & USBC_XFERCOMPLMSK)
{
if(boot_UsbContinueTransfert(
HAL_USB_EP_DIRECTION_IN(i)))
{
boot_UsbCallbackEp
(HAL_USB_EP_DIRECTION_IN(i),
HAL_USB_CALLBACK_TYPE_TRANSMIT_END, 0);
}
}
if(statusEp & USBC_TIMEOUTMSK)
{
// Clear Timeout interupt
BOOT_PROFILE_PULSE(BOOT_USB_TIMEOUT_IN);
boot_UsbCancelTransfert(HAL_USB_EP_DIRECTION_IN(i));
hwp_usbc->DIEPnCONFIG[i].DIEPINT = USBC_SETUPMK;
}
}
}
}
BOOT_PROFILE_FUNCTION_EXIT(boot_UsbIrqHandlerI);
}
if(status & USBC_OEPINT) // RX
{
data = hwp_usbc->DAINT;
BOOT_PROFILE_FUNCTION_ENTER(boot_UsbIrqHandlerO);
for(i = 0; i < g_BootUsbVar.NbEp; ++i)
{
if((data>>(i+16))&1)
{
if(i == 0)
{
statusEp = hwp_usbc->DOEPINT0;
if(statusEp & USBC_SETUPMK)
{
BOOT_PROFILE_FUNCTION_ENTER(boot_UsbIrqHandlerOsp);
// Decode Ep0 command
boot_UsbDecodeEp0Packet();
// Clear Setup interrupt
hwp_usbc->DOEPINT0 = USBC_SETUPMK;
BOOT_PROFILE_FUNCTION_EXIT(boot_UsbIrqHandlerOsp);
}
if(statusEp & USBC_XFERCOMPLMSK)
{
BOOT_PROFILE_FUNCTION_ENTER(boot_UsbIrqHandlerOcp);
// Clear transfert completed interrupt
hwp_usbc->DOEPINT0 = USBC_XFERCOMPLMSK;
// Decode Ep0 command
boot_UsbDecodeEp0Packet();
BOOT_PROFILE_FUNCTION_EXIT(boot_UsbIrqHandlerOcp);
}
}
else
{
statusEp = hwp_usbc->DOEPnCONFIG[i-1].DOEPINT;
hwp_usbc->DOEPnCONFIG[i-1].DOEPINT = statusEp;
if(statusEp & USBC_XFERCOMPLMSK)
{
if(boot_UsbContinueTransfert(
HAL_USB_EP_DIRECTION_OUT(i)))
{
boot_UsbCallbackEp
(HAL_USB_EP_DIRECTION_OUT(i),
HAL_USB_CALLBACK_TYPE_RECEIVE_END, 0);
}
}
}
}
}
BOOT_PROFILE_FUNCTION_EXIT(boot_UsbIrqHandlerO);
}
BOOT_PROFILE_FUNCTION_EXIT(boot_UsbIrqHandler);
}
PUBLIC VOID boot_UsbOpen(HAL_USB_GETDESCRIPTOR_CALLBACK_T callback)
{
hwp_usbc->GRSTCTL = USBC_CSFTRST;
boot_UsbInit();
g_BootUsbVar.DeviceCallback = callback;
boot_UsbConfig();
}
PUBLIC VOID boot_UsbEpStall(UINT8 ep, BOOL stall)
{
UINT8 epNum;
REG32* diepctl;
REG32* doepctl;
epNum = HAL_USB_EP_NUM(ep);
// Select ctl register
if(epNum == 0)
{
diepctl = &hwp_usbc->DIEPCTL0;
doepctl = &hwp_usbc->DOEPCTL0;
}
else
{
diepctl = &hwp_usbc->DIEPnCONFIG[epNum-1].DIEPCTL;
doepctl = &hwp_usbc->DOEPnCONFIG[epNum-1].DOEPCTL;
}
// Select direction
if(HAL_USB_IS_EP_DIRECTION_IN(ep))
{
if(stall == TRUE)
{
if(*diepctl & USBC_EPENA)
{
*diepctl |= USBC_STALL | USBC_EPDIS;
}
else
{
*diepctl |= USBC_STALL;
}
}
else
{
*diepctl &= ~(USBC_STALL | USBC_EPDIS | USBC_EPENA);
*diepctl |= USBC_SETD0PID;
}
}
else
{
if(stall == TRUE)
{
*doepctl |= USBC_STALL;
}
else
{
*doepctl &= ~(USBC_STALL | USBC_EPDIS | USBC_EPENA);
}
}
}
PUBLIC INT32 boot_UsbRecv(UINT8 ep, UINT8* buffer, UINT16 size, UINT32 flag)
{
UINT8 epNum;
UINT32 activeEp;
epNum = HAL_USB_EP_NUM(ep);
if(epNum == 0)
{
activeEp = USBC_USBACTEP;
}
else
{
activeEp = hwp_usbc->DOEPnCONFIG[epNum-1].DOEPCTL & USBC_USBACTEP;
}
if(activeEp &&
boot_UsbStartTransfert(HAL_USB_EP_DIRECTION_OUT(ep), buffer, size, flag)
== 0)
{
return(size);
}
return(-1);
}
PUBLIC INT32 boot_UsbSend(UINT8 ep, UINT8* buffer, UINT16 size, UINT32 flag)
{
UINT8 epNum;
UINT32 activeEp;
epNum = HAL_USB_EP_NUM(ep);
if(epNum == 0)
{
activeEp = USBC_USBACTEP;
}
else
{
activeEp = hwp_usbc->DIEPnCONFIG[epNum-1].DIEPCTL & USBC_USBACTEP;
}
if(activeEp &&
boot_UsbStartTransfert(HAL_USB_EP_DIRECTION_IN(ep), buffer, size, flag)
== 0)
{
return(size);
}
return(-1);
}
PUBLIC VOID boot_UsbCompletedCommand(VOID)
{
switch(g_BootUsbVar.Ep0State)
{
case EP0_STATE_STATUS_OUT:
boot_UsbStatusOut();
break;
case EP0_STATE_STATUS_IN:
boot_UsbStatusIn();
break;
default:
break;
}
}
PUBLIC VOID boot_UsbEpEnableInterrupt(UINT8 ep, BOOL enable)
{
UINT8 epNum;
epNum = HAL_USB_EP_NUM(ep);
if(enable == TRUE)
{
if(HAL_USB_IS_EP_DIRECTION_IN(ep))
{
hwp_usbc->DAINTMSK |= (1<<epNum);
}
else
{
hwp_usbc->DAINTMSK |= (1<<(epNum+16));
}
}
else
{
if(HAL_USB_IS_EP_DIRECTION_IN(ep))
{
hwp_usbc->DAINTMSK &= ~(1<<epNum);
}
else
{
hwp_usbc->DAINTMSK &= ~(1<<(epNum+16));
}
}
}
PUBLIC UINT16 boot_UsbEpRxTransferedSize(UINT8 ep)
{
UINT8 epNum;
epNum = HAL_USB_EP_NUM(ep);
return(-g_BootUsbVar.OutTransfert[epNum].size);
}
PUBLIC BOOL boot_UsbEpTransfertDone(UINT8 ep)
{
UINT8 epNum;
BOOL value = FALSE;
REG32* reg;
epNum = HAL_USB_EP_NUM(ep);
if(HAL_USB_IS_EP_DIRECTION_IN(ep))
{
if(g_BootUsbVar.InTransfert[epNum].size <= 0)
{
return(TRUE);
}
if(epNum == 0)
{
reg = &hwp_usbc->DIEPINT0;
}
else
{
reg = &hwp_usbc->DIEPnCONFIG[epNum-1].DIEPINT;
}
if(*reg&USBC_TIMEOUTMSK)
{
*reg = USBC_TIMEOUTMSK;
boot_UsbCancelTransfert(ep);
BOOT_PROFILE_PULSE(BOOT_USB_TIMEOUT_IN);
value = TRUE;
}
}
else
{
if(epNum == 0)
{
reg = &hwp_usbc->DOEPINT0;
}
else
{
reg = &hwp_usbc->DOEPnCONFIG[epNum-1].DOEPINT;
}
}
if(*reg&USBC_XFERCOMPL)
{
*reg = USBC_XFERCOMPL;
value = (boot_UsbContinueTransfert(ep) == 1);
}
return(value);
}
PUBLIC VOID boot_UsbClose(VOID)
{
g_BootUsbVar.Ep0State = EP0_STATE_IDLE;
g_BootUsbVar.NbString = 0;
g_BootUsbVar.Desc = 0;
hwp_usbc->GAHBCFG = 0;
hwp_usbc->GUSBCFG = 0;
g_BootUsbVar.DeviceCallback = 0;
boot_UsbClrConfig();
boot_UsbResetTransfert();
}
PUBLIC VOID boot_UsbReset(VOID)
{
hwp_usbc->GRSTCTL = USBC_CSFTRST;
boot_UsbInit();
boot_UsbConfig();
}
| C | CL | fccfc117c4524f324f39192e4cd58862f7b98577c942b2d277f03f6b1466f630 |
/*
A simple obj 3D file format mesh loader library
Copyright (c) 2015 Md Imam Hossain
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Md Imam Hossain
[email protected]
*/
#include "openobj3d.h"
int ooj_loadmesh (char *obj_filename, OOJ_Mesh *mo)
{
FILE *fp = NULL;
FILE *ff = NULL;
char scanline[1024];
char mat_file[128];
char obj_file[128];
long i = 0;
OOJ_MaterialG mg;
long current_texture = 1;
OOJ_Vertex vg;
OOJ_TexCoordG tg;
OOJ_Vertex nm;
char current_material[128];
int take_tex = 0;
mg.slot = 0;
mg.m = NULL;
memset (scanline, '\0', 1024);
memset (mat_file, '\0', 128);
strcat (mat_file, obj_filename);
strcat (mat_file, ".mtl");
fp = fopen (mat_file, "r");
if (fp == NULL) {
return 1;
}
while (fgets (scanline, 1023, fp) != NULL) {
if (scanline[0] == 'n' && scanline[1] == 'e' && scanline[2] == 'w') {
char *mnone = NULL;
char tmpstr[128];
mg.m = (OOJ_Material *) realloc (mg.m, ((mg.slot + 1) * sizeof (OOJ_Material)));
if (mg.m == NULL) {
fclose(fp);
return (1);
}
memset (mg.m[mg.slot].name, '\0', 128);
sscanf (scanline, "newmtl %s", mg.m[mg.slot].name);
memset (mg.m[mg.slot].texture, '\0', 128);
memset (tmpstr, '\0', 128);
strcpy (tmpstr, mg.m[mg.slot].name);
mnone = strtok (tmpstr, "_");
mnone = strtok (NULL, "_");
if (mnone == NULL) take_tex = 1;
else {
if (strcmp (mnone, "NONE") == 0) {
take_tex = 0;
mg.m[mg.slot].texture_id = -1;
}
else take_tex = 1;
}
mg.slot += 1;
}
else if (scanline[0] == 'K' && scanline[1] == 'a') {
sscanf (scanline, "Ka %f %f %f", &mg.m[mg.slot-1].ambient.red, &mg.m[mg.slot-1].ambient.green, &mg.m[mg.slot-1].ambient.blue);
}
else if (scanline[0] == 'K' && scanline[1] == 'd') {
sscanf (scanline, "Kd %f %f %f", &mg.m[mg.slot-1].diffuse.red, &mg.m[mg.slot-1].diffuse.green, &mg.m[mg.slot-1].diffuse.blue);
}
else if (scanline[0] == 'K' && scanline[1] == 's') {
sscanf (scanline, "Ks %f %f %f", &mg.m[mg.slot-1].specular.red, &mg.m[mg.slot-1].specular.green, &mg.m[mg.slot-1].specular.blue);
}
else if (scanline[0] == 'm' && scanline[1] == 'a' && scanline[2] == 'p' && take_tex == 1) {
sscanf (scanline, "map_Kd %s", mg.m[mg.slot-1].texture);
mg.m[mg.slot-1].texture_id = current_texture;
current_texture += 1;
}
}
fclose (fp);
memset (obj_file, '\0', 128);
strcat (obj_file, obj_filename);
strcat (obj_file, ".obj");
ff = fopen (obj_file, "r");
if (ff == NULL) {
free (mg.m);
return 1;
}
vg.slot = 0;
vg.v = NULL;
nm.slot = 0;
nm.v = NULL;
tg.slot = 0;
tg.t = NULL;
mo->f = NULL;
mo->slot = 0;
mo->tex_num = 0;
mo->mat_num = 0;
memset (mo->textures, '\0', 16384);
memset (scanline, '\0', 1024);
while (fgets (scanline, 1023, ff) != NULL) {
if (scanline[0] == 'v' && scanline[1] == ' ') {
vg.v = (OOJ_Coord3D *) realloc (vg.v, (vg.slot + 1) * sizeof (OOJ_Coord3D));
if (vg.v == NULL) {
if (tg.t != NULL) free (tg.t);
if (nm.v != NULL) free (nm.v);
if (mo->f != NULL) free (mo->f);
if (mg.m != NULL) free (mg.m);
fclose(ff);
return 1;
}
sscanf (scanline, "v %f %f %f", &vg.v[vg.slot].x, &vg.v[vg.slot].y, &vg.v[vg.slot].z);
vg.slot += 1;
}
else if (scanline[0] == 'v' && scanline[1] == 't') {
tg.t = (OOJ_TexCoord *) realloc (tg.t, (tg.slot + 1) * sizeof (OOJ_TexCoord));
if (tg.t == NULL) {
if (vg.v != NULL) free (vg.v);
if (nm.v != NULL) free (nm.v);
if (mo->f != NULL) free (mo->f);
if (mg.m != NULL) free (mg.m);
fclose(ff);
return 1;
}
sscanf (scanline, "vt %f %f", &tg.t[tg.slot].u, &tg.t[tg.slot].v);
tg.t[tg.slot].v = 1 - tg.t[tg.slot].v;
tg.slot += 1;
}
else if (scanline[0] == 'v' && scanline[1] == 'n') {
nm.v = (OOJ_Coord3D *) realloc (nm.v, (nm.slot + 1) * sizeof (OOJ_Coord3D));
if (nm.v == NULL) {
if (tg.t != NULL) free (tg.t);
if (vg.v != NULL) free (vg.v);
if (mo->f != NULL) free (mo->f);
if (mg.m != NULL) free (mg.m);
fclose(ff);
return 1;
}
sscanf (scanline, "vn %f %f %f", &nm.v[nm.slot].x, &nm.v[nm.slot].y, &nm.v[nm.slot].z);
nm.slot += 1;
}
else if (scanline[0] == 'u' && scanline[1] == 's' && scanline[2] == 'e') {
memset (current_material, '\0', 128);
sscanf (scanline, "usemtl %s", current_material);
}
else if (scanline[0] == 'f' && scanline[1] == ' ') {
long v1, v2, v3, t1, t2, t3, n1, n2, n3;
mo->f = (OOJ_Face *) realloc (mo->f, (mo->slot + 1) * sizeof (OOJ_Face));
if (mo->f == NULL) {
if (tg.t != NULL) free (tg.t);
if (nm.v != NULL) free (nm.v);
if (vg.v != NULL) free (vg.v);
if (mg.m != NULL) free (mg.m);
fclose(ff);
return 1;
}
sscanf (scanline, "f %ld/%ld/%ld %ld/%ld/%ld %ld/%ld/%ld", &v1, &t1, &n1, &v2, &t2, &n2, &v3, &t3, &n3);
mo->f[mo->slot].v[0].x = vg.v[v1-1].x;
mo->f[mo->slot].v[0].y = vg.v[v1-1].y;
mo->f[mo->slot].v[0].z = vg.v[v1-1].z;
mo->f[mo->slot].v[1].x = vg.v[v2-1].x;
mo->f[mo->slot].v[1].y = vg.v[v2-1].y;
mo->f[mo->slot].v[1].z = vg.v[v2-1].z;
mo->f[mo->slot].v[2].x = vg.v[v3-1].x;
mo->f[mo->slot].v[2].y = vg.v[v3-1].y;
mo->f[mo->slot].v[2].z = vg.v[v3-1].z;
mo->f[mo->slot].t[0].u = tg.t[t1-1].u;
mo->f[mo->slot].t[0].v = tg.t[t1-1].v;
mo->f[mo->slot].t[1].u = tg.t[t2-1].u;
mo->f[mo->slot].t[1].v = tg.t[t2-1].v;
mo->f[mo->slot].t[2].u = tg.t[t3-1].u;
mo->f[mo->slot].t[2].v = tg.t[t3-1].v;
mo->f[mo->slot].n[0].x = nm.v[n1-1].x;
mo->f[mo->slot].n[0].y = nm.v[n1-1].y;
mo->f[mo->slot].n[0].z = nm.v[n1-1].z;
mo->f[mo->slot].n[1].x = nm.v[n2-1].x;
mo->f[mo->slot].n[1].y = nm.v[n2-1].y;
mo->f[mo->slot].n[1].z = nm.v[n2-1].z;
mo->f[mo->slot].n[2].x = nm.v[n3-1].x;
mo->f[mo->slot].n[2].y = nm.v[n3-1].y;
mo->f[mo->slot].n[2].z = nm.v[n3-1].z;
if (strlen (current_material) > 1) {
strcpy (mo->f[mo->slot].material, current_material);
for (i = 0; i < mg.slot; i++) {
if (strcmp (mo->f[mo->slot].material, mg.m[i].name) == 0) {
mo->f[mo->slot].ambient.red = mg.m[i].ambient.red;
mo->f[mo->slot].ambient.green = mg.m[i].ambient.green;
mo->f[mo->slot].ambient.blue = mg.m[i].ambient.blue;
mo->f[mo->slot].diffuse.red = mg.m[i].diffuse.red;
mo->f[mo->slot].diffuse.green = mg.m[i].diffuse.green;
mo->f[mo->slot].diffuse.blue = mg.m[i].diffuse.blue;
mo->f[mo->slot].specular.red = mg.m[i].specular.red;
mo->f[mo->slot].specular.green = mg.m[i].specular.green;
mo->f[mo->slot].specular.blue = mg.m[i].specular.blue;
strcpy (mo->f[mo->slot].texture, mg.m[i].texture);
if (strlen (mg.m[i].texture) > 1) mo->f[mo->slot].texture_id = mg.m[i].texture_id;
else mo->f[mo->slot].texture_id = 0;
}
}
}
mo->slot += 1;
}
}
mo->mat_num = mg.slot;
for (i = 0; i < mg.slot; i += 1) {
if (mg.m[i].texture_id > 0) mo->tex_num += 1;
}
for (i = 0; i < mg.slot; i += 1) {
if (strlen(mg.m[i].texture) > 1) {
strcat (mo->textures, mg.m[i].texture);
strcat (mo->textures, " ");
}
}
fclose (ff);
free (mg.m);
free (vg.v);
free (tg.t);
free (nm.v);
return 0;
}
| C | CL | 93beb597cb00b6c619cbcab17dd5e54ef24b693b83290385beb71f04cd36d1f6 |
#include "SPI_Slave.h"
#include "CRC16.h"
#include "main.h"
#include <string.h>
#define SPI1_MOSI_PIN GPIO_Pin_7
#define SPI1_MISO_PIN GPIO_Pin_6
#define SPI1_SCLK_PIN GPIO_Pin_5
#define SPI1_NSS_PIN GPIO_Pin_4
#define SPI1_GPIO GPIOA
#define SPI1_GPIO_PeriphClock RCC_APB2Periph_GPIOA
#define SPI1_PeriphClock RCC_APB2Periph_SPI1
void DMA1_Spi1_Init(void);
void Timer_Config(void);
void SPI_Slave_Init(void)
{
SPI_InitTypeDef SPI_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
// Enable SPI1 and GPIO clocks
RCC_APB2PeriphClockCmd(SPI1_PeriphClock|RCC_APB2Periph_AFIO|SPI1_GPIO_PeriphClock, ENABLE);//SPI_FLASH_SPI Periph clock enable
SPI_Cmd(SPI1, DISABLE);
// Configure SPI pins: MISO
GPIO_InitStructure.GPIO_Pin = SPI1_MISO_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;//复用推免输出
GPIO_Init(SPI1_GPIO, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = SPI1_MOSI_PIN|SPI1_SCLK_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(SPI1_GPIO, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = SPI1_NSS_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(SPI1_GPIO, &GPIO_InitStructure);
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Slave;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_16b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Hard;//SPI_NSS_Hard;SPI_NSS_Soft
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI1, &SPI_InitStructure);
//Timer_Config();
//SPI_I2S_ITConfig(SPI1, SPI_I2S_IT_RXNE, ENABLE);
DMA1_Spi1_Init();
DMA_Cmd(DMA1_Channel2,ENABLE);
DMA_Cmd(DMA1_Channel3,ENABLE);
SPI_Cmd(SPI1, ENABLE); //Enable SPI1
}
char flag=1;
volatile u16 data;
void TIM2_IRQHandler(void)
{
//TIM2->CR1 &= ~TIM_CR1_CEN;
TIM2->SR = (uint16_t)~TIM_FLAG_Update;
if(flag)
{
flag=0;
GPIO_ResetBits(GPIOB, GPIO_Pin_12);
}else{
flag=1;
GPIO_SetBits(GPIOB, GPIO_Pin_12);
}
rt_kprintf("\r\n IRQ 0x%x\r\n",data);
}
//DMA传输尺寸
#define Pkagesiz 6
#define SPI1DMA_TRRXSIZ 20
#define SPI1DMA_TRTXSIZ 10
u16 SPI1_RCVDAT[SPI1DMA_TRRXSIZ]={0};
u16 SPI1_TXDDAT[SPI1DMA_TRTXSIZ]={0};
u16 parFramedata[SPI1DMA_TRRXSIZ]={0};
#define SPI_SLAVE_DMA DMA1_Channel2
static u16 curr_recv_index=0;
static u16 last_recv_index=0;
static u16 recv_len=0;
volatile u8 bHandleSPIFrame=0;
static u16 * pMem ;
void DMA1_Spi1_Init(void)
{
DMA_InitTypeDef DMA1_Init;
NVIC_InitTypeDef NVIC_InitSPI1TX,NVIC_InitTyp;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1,ENABLE);
EXTI_InitTypeDef EXTI_InitTyp;
//NVIC_InitTyp.NVIC_IRQChannel = DMA1_Channel3_IRQn;
//NVIC_InitTyp.NVIC_IRQChannelPreemptionPriority = 1;
//NVIC_InitTyp.NVIC_IRQChannelSubPriority = 2;
//NVIC_InitTyp.NVIC_IRQChannelCmd = ENABLE;
//NVIC_Init(&NVIC_InitTyp);
NVIC_InitTyp.NVIC_IRQChannel = DMA1_Channel2_IRQn;
NVIC_InitTyp.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitTyp.NVIC_IRQChannelSubPriority = 2;
NVIC_InitTyp.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitTyp);
//DMA_SPI_RX SPI->RAM的数据传输
DMA_DeInit(DMA1_Channel2);
DMA1_Init.DMA_PeripheralBaseAddr = (u32)&SPI1->DR;//启动传输前装入实际RAM地址
DMA1_Init.DMA_MemoryBaseAddr = (u32)SPI1_RCVDAT;
DMA1_Init.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA1_Init.DMA_BufferSize = SPI1DMA_TRRXSIZ;//DMA_MemoryDataSize个数
DMA1_Init.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA1_Init.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA1_Init.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA1_Init.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA1_Init.DMA_Mode = DMA_Mode_Normal;
DMA1_Init.DMA_Priority = DMA_Priority_High;
DMA1_Init.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel2,&DMA1_Init); //对DMA通道3进行初始化
//DMA_SPI_TX RAM->SPI的数据传输
DMA_DeInit(DMA1_Channel3);
DMA1_Init.DMA_PeripheralBaseAddr = (u32)&SPI1->DR;//启动传输前装入实际RAM地址
DMA1_Init.DMA_MemoryBaseAddr = (u32)&SPI1_TXDDAT;
DMA1_Init.DMA_DIR = DMA_DIR_PeripheralDST;
DMA1_Init.DMA_BufferSize = SPI1DMA_TRTXSIZ;
DMA1_Init.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA1_Init.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA1_Init.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA1_Init.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA1_Init.DMA_Mode = DMA_Mode_Normal;
DMA1_Init.DMA_Priority = DMA_Priority_High;
DMA1_Init.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel3,&DMA1_Init); //对DMA通道3进行初始化
SPI_I2S_DMACmd(SPI1,SPI_I2S_DMAReq_Rx,ENABLE); //使能SPI的DMA接收请求
SPI_I2S_DMACmd(SPI1,SPI_I2S_DMAReq_Tx,ENABLE); //使能SPI的DMA发送请求
DMA_ITConfig(DMA1_Channel2, DMA_IT_TC, ENABLE);//使能DMA传输完成中断
//DMA_ITConfig(DMA1_Channel3, DMA_IT_TC, ENABLE);//使能DMA传输完成中断
curr_recv_index=0;
pMem = SPI1_RCVDAT;
NVIC_InitTyp.NVIC_IRQChannel = EXTI4_IRQn; //EXTI中断通道
NVIC_InitTyp.NVIC_IRQChannelPreemptionPriority=2; //抢占优先级
NVIC_InitTyp.NVIC_IRQChannelSubPriority =3; //子优先级
NVIC_InitTyp.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitTyp); //根据指定的参数初始化VIC寄存器
EXTI_InitTyp.EXTI_Line=EXTI_Line4;
EXTI_InitTyp.EXTI_Mode=EXTI_Mode_Interrupt;
EXTI_InitTyp.EXTI_Trigger=EXTI_Trigger_Rising;
EXTI_InitTyp.EXTI_LineCmd=ENABLE;
EXTI_Init(&EXTI_InitTyp);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA,GPIO_PinSource4);
SPI1_TXDDAT[0]=1;
SPI1_TXDDAT[1]=2;
SPI1_TXDDAT[2]=3;
SPI1_TXDDAT[3]=4;
SPI1_TXDDAT[4]=5;
SPI1_TXDDAT[5]=6;
SPI1_TXDDAT[6]=7;
SPI1_TXDDAT[7]=8;
SPI1_TXDDAT[8]=9;
SPI1_TXDDAT[9]=10;
}
volatile static u8 bDMAFlag=0;
extern struct rt_messagequeue alarm_mq;
void EXTI4_IRQHandler(void)
{
volatile u16 * src_ptr=0;
volatile u16 CNT= (u16)(DMA1_Channel2->CNDTR);
alarm_data msg_alarm_data={0};
u32 tmp32=0;
u8 j=0;
u16 i =0;
if(EXTI_GetITStatus(EXTI_Line4)==1)
{
//rt_kprintf("\r\nCNDTR%d\r\n",CNT);
//拷贝接收数据
recv_len = SPI1DMA_TRRXSIZ - SPI_SLAVE_DMA->CNDTR;
memcpy( parFramedata , SPI1_RCVDAT, recv_len<<1);
SPI_SLAVE_DMA->CCR &= (uint16_t)(~DMA_CCR1_EN);
SPI_SLAVE_DMA->CMAR = (u32) SPI1_RCVDAT;
SPI_SLAVE_DMA->CNDTR = SPI1DMA_TRRXSIZ;
SPI_SLAVE_DMA->CCR |= DMA_CCR1_EN;
//准备下次返回的数据
DMA1_Channel3->CCR &= (uint16_t)(~DMA_CCR1_EN);
DMA1_Channel3->CNDTR = SPI1DMA_TRTXSIZ-1;
SPI1->DR = SPI1_TXDDAT[0];
DMA1_Channel3->CMAR = (u32)&SPI1_TXDDAT[1];
DMA1_Channel3->CCR |= DMA_CCR1_EN;
#if(using_debug)
rt_kprintf("recv:\n");
for(i =0 ;i<recv_len;i++)
{
rt_kprintf("%4x;",SPI1_RCVDAT[i]);
}
rt_kprintf("\n");
#endif
if((0x55AA==parFramedata[0]))
{
if(Pkagesiz==recv_len)
{
if(funCRC16((u8 *)parFramedata,(Pkagesiz-1)<<1)==parFramedata[Pkagesiz-1])
{
tmp32=parFramedata[3];//位置值高半字
tmp32=tmp32<<16;
tmp32=tmp32+parFramedata[2];//位置值低半字
msg_alarm_data.type = (parFramedata[1]>>8);//高字节报警类型
msg_alarm_data.chanel = parFramedata[1]&0x00FF;//低字节通道号
msg_alarm_data.pos = tmp32;
msg_alarm_data.temp=parFramedata[4]%0x0100;//温度值
rt_mq_send(&alarm_mq,&msg_alarm_data,sizeof(msg_alarm_data));
}
}
}
EXTI_ClearITPendingBit(EXTI_Line4);
}
}
//SPI1 DMA channel2 中断
void DMA1_Channel2_IRQHandler(void)//接收中断
{
if(DMA_GetFlagStatus(DMA1_IT_TC2) == SET)
{
bDMAFlag=1;
DMA_ClearITPendingBit(DMA1_IT_TC2);
}
}
//#define StartTimer() { TIM2->EGR = TIM_PSCReloadMode_Immediate;TIM2->CR1 |= TIM_CR1_CEN;}
//void SPI1_IRQHandler(void)
//{
// static u16 i=0;
// if(SPI_I2S_GetITStatus(SPI1, SPI_I2S_IT_RXNE) == SET)
// {
//
// // StartTimer();
// SPI_I2S_ClearITPendingBit(SPI1, SPI_I2S_IT_RXNE);
// }
//}
//void Timer_Config(void)
//{
// TIM_TimeBaseInitTypeDef TIM_TimeBase;
// RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
// TIM_DeInit(TIM2);
// TIM_TimeBase.TIM_Period=4000-1; //自动重装载寄存器的值 4ms
// TIM_TimeBase.TIM_Prescaler=(72-1); //时钟预分频数
// TIM_TimeBase.TIM_ClockDivision=TIM_CKD_DIV1; //采样分频
// TIM_TimeBase.TIM_CounterMode=TIM_CounterMode_Up; //向上计数模式
// TIM_TimeBaseInit(TIM2,&TIM_TimeBase);
// TIM_ClearFlag(TIM2,TIM_FLAG_Update); //清除溢出中断标志
// TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
// // TIM_Cmd(TIM2,ENABLE); //开启时钟
//}
//SPI 数据包定义 以 U16为最小单位
// header Lenth data tail
// 1个长度 1个长度 2个长度 1个长度
// 0X55AA 2 xx xx CRC16 | C | CL | a351b9521cb9b7e572f0a7ba2230144991ba7a1081bb63e7021052dc13a82d0f |
/*
File: lab-mar-22.c simple implementation of a binary search tree
keys are strings
partial solution to lab Mar 22/24 CS1023 Winter 2011
*/
#include "strlib.h" //for StringCompare function
typedef struct nodeT
{
string key;
struct nodeT *left, *right;
} nodeT, *treeT;
/*function prototypes*/
treeT FindNode(treeT t, string key);
void InsertNode(treeT *tptr, string key);
void DisplayTree(treeT t);
void PostOrderWalk(treeT t);
void PreOrderWalk(treeT t);
int main()
{
//create a languageTree
treeT languageTree = NULL;
//insert some values (programming languages)
InsertNode(&languageTree, "5");
InsertNode(&languageTree, "4");
InsertNode(&languageTree, "6");
InsertNode(&languageTree, "1");
InsertNode(&languageTree, "2");
InsertNode(&languageTree, "3");
InsertNode(&languageTree, "7");
InsertNode(&languageTree, "8");
//display the tree using InOrder, PreOrder and PostOrder traversal
printf("\nIn Order Traversal\n");
DisplayTree(languageTree);
printf("\nPre Order Traversal\n");
PreOrderWalk(languageTree);
printf("\nPost Order Traversal\n");
PostOrderWalk(languageTree);
FreeBlock(languageTree);
}
treeT FindNode(treeT t, string key)
{
int sign;
if (t==NULL) return NULL;
sign = StringCompare(key, t->key);
if (sign == 0) return(t);
if (sign < 0)
{
return(FindNode(t->left, key));
} else
return(FindNode(t->right, key));
}
void InsertNode(treeT *tptr, string key)
{
treeT t;
int sign;
t = *tptr;
if (t == NULL)
{
t = New(treeT);
t->key = CopyString(key);
t->left = t->right = NULL;
*tptr = t;
return;
}
sign = StringCompare(key, t->key);
if (sign ==0 ) return;
if (sign < 0)
InsertNode(&t->left, key);
else
InsertNode(&t->right, key);
}
// In Order traversal of the tree
void DisplayTree(treeT t)
{
if (t != NULL)
{
DisplayTree(t->left);
printf("%s\n", t->key);
DisplayTree(t->right);
}
}
// Pre Order traversal of the tree
void PreOrderWalk(treeT t)
{
if (t != NULL)
{
printf("%s\n", t->key);
PreOrderWalk(t->left);
PreOrderWalk(t->right);
}
}
// In Order traversal of the tree
void PostOrderWalk(treeT t)
{
if (t != NULL)
{
PostOrderWalk(t->left);
PostOrderWalk(t->right);
printf("%s\n", t->key);
}
}
//Another compression technique is COMPAX. In COMPAX, bitmaps are first
//compressed using WAH, and then are further compressed by encoding words as
//LFL and FLF words. In these patterns, L words are dirty words that
//contain a single dirty byte and F words are dirty words that always have a
//last dirty byte. F words are compressed 0-fill words. unlikely to form
//in their context. They have dirty words which they call literal words and
//label as L and 0-fill words which are labelled as F. They additionally
//introduce the LFL, and FLF word, that further compress their WAH encoded
//indices
| C | CL | e4cab1452178da67e28fcd23f56d99b4fa2f44966d94e7027de37bef3faeb7e3 |
/**
* @file
* kernel login.
*
* VxWorks compatibility layer in SylixOS.
*
* Copyright (c) 2001-2014 SylixOS Group.
* All rights reserved.
*
* Author: Han.hui <[email protected]>
*/
#define __SYLIXOS_KERNEL
#include "vxWorksCommon.h"
/*
* return the WIND kernel revision string
*/
char *kernelVersion (void)
{
return ("WIND version 2.13");
}
/*
* enable round-robin selection
*/
STATUS kernelTimeSlice (int ticks)
{
UINT16 usSlice = (UINT16)ticks;
API_ThreadSetSlice(API_ThreadIdSelf(), usSlice);
return (OK);
}
/*
* get the time slice ticks
*/
STATUS kernelTimeSliceGet (ULONG *pTimeSlice)
{
UINT16 usSlice;
if (pTimeSlice) {
API_ThreadGetSlice(API_ThreadIdSelf(), &usSlice);
*pTimeSlice = (ULONG)usSlice;
return (OK);
}
return (ERROR);
}
/*
* install VxWorks Round Robin implementation
*/
STATUS kernelRoundRobinInstall (void)
{
return (OK);
}
/*
* non-bootstrap processor entry point into Wind kernel
*/
STATUS kernelCpuEnable (unsigned int cpuToEnable)
{
return (OK);
}
/*
* determine whether the specified CPU is idle
*/
BOOL kernelIsCpuIdle (unsigned int cpu)
{
BOOL bRet;
PLW_CLASS_CPU pcpu;
if (cpu >= LW_NCPUS) {
return (LW_TRUE);
}
__KERNEL_ENTER();
pcpu = LW_CPU_GET(cpu);
if (LW_CPU_IS_ACTIVE(pcpu)) {
bRet = LW_TRUE;
} else {
if (pcpu->CPU_ptcbTCBCur->TCB_ucPriority == LW_PRIO_IDLE) {
bRet = LW_TRUE;
} else {
bRet = LW_FALSE;
}
}
__KERNEL_EXIT();
return (bRet);
}
/*
* determine whether all enabled processors are idle
*/
BOOL kernelIsSystemIdle (void)
{
return (LW_FALSE);
}
/*
* end
*/
| C | CL | 5c438de5a3f512a935e188acf599740aae105f65778dc1bf9505a777bb434116 |
../../../../../../GoogleProtobuf/src/google/protobuf/io/printer.h | C | CL | b107ee3abbabfbcdf4714ccc091b8fc179bbc53bec5c0478dfa746a2955657b1 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int u8 ;
typedef int /*<<< orphan*/ temp_buf ;
struct ds3232 {int /*<<< orphan*/ regmap; } ;
struct device {int dummy; } ;
typedef int s16 ;
/* Variables and functions */
int /*<<< orphan*/ DS3232_REG_TEMPERATURE ;
struct ds3232* dev_get_drvdata (struct device*) ;
int regmap_bulk_read (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int*,int) ;
__attribute__((used)) static int ds3232_hwmon_read_temp(struct device *dev, long int *mC)
{
struct ds3232 *ds3232 = dev_get_drvdata(dev);
u8 temp_buf[2];
s16 temp;
int ret;
ret = regmap_bulk_read(ds3232->regmap, DS3232_REG_TEMPERATURE, temp_buf,
sizeof(temp_buf));
if (ret < 0)
return ret;
/*
* Temperature is represented as a 10-bit code with a resolution of
* 0.25 degree celsius and encoded in two's complement format.
*/
temp = (temp_buf[0] << 8) | temp_buf[1];
temp >>= 6;
*mC = temp * 250;
return 0;
} | C | CL | d3753b4d509ce19285455195ed2ab95ddd3f59e51a4dccd9cbffef3fcf63b396 |
/*
* Coefficients for vector log2f
*
* Copyright (c) 2022-2023, Arm Limited.
* SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
*/
#include "math_config.h"
/* See tools/v_log2f.sollya for the algorithm used to generate these
coefficients. */
const struct v_log2f_data __v_log2f_data
= {.poly = {0x1.715476p0f, /* (float)(1 / ln(2)). */
-0x1.715458p-1f, 0x1.ec701cp-2f, -0x1.7171a4p-2f, 0x1.27a0b8p-2f,
-0x1.e5143ep-3f, 0x1.9d8ecap-3f, -0x1.c675bp-3f, 0x1.9e495p-3f}};
| C | CL | 0f15517b25efd9dfd732b175a29c8573a28670cfc8d65d2d4908fb7319f03c9d |
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ElementArray.h"
#include "Error.h"
#include "ErrorLL.h"
#include "Type.h"
#include "Hash.h"
#include "PreDef.h"
#include "SymbolAll.h"
/*For error reporting*/
extern int yylineno;
extern int colno;
static char *errMsg;
struct Error *e;
/*
* Given a linked list of ProxySymbols, returns the type which results
* from using the linked list of ProxySymbols to access the array given
* by var.
*
* Parameters:
* var: symbol for array variable to be indexed into
* indices: linked-list of array indices to use to index into var
*
* Return:
* A Symbol of kind TYPE_KIND that is the expected resultant type of the
* array indexing.
* NULL on error
*
* TODO: if index is const not part of scalar, see if its value falls in the
* allowable range.
*
*/
Symbol *isValidArrayAccess(ProxySymbol *var, ProxySymbol *indices) {
Symbol *arrayTypeSym = NULL;
Symbol *indexTypeSym = NULL;
Symbol *returnTypeSym = NULL;
Symbol *arg = indices;
int typeErr = 0;
if ((var == NULL)||(indices == NULL)) {
err(EXIT_FAILURE, "Tried to do array access with NULL args.");
}
arrayTypeSym = getTypeSym(var);
if (getType(arrayTypeSym) != ARRAY_T) {
errMsg = customErrorString("Tried to index into %s, which is "
"of type %s, and not an array type.",
arg->name,
typeToString(getType(arrayTypeSym)));
recordError(errMsg, yylineno, colno, SEMANTIC);
return NULL;
}
indexTypeSym = getArrayIndexSym(arrayTypeSym);
while ( (arg) && (getType(arrayTypeSym) == ARRAY_T)) {
switch (getType(indexTypeSym)) {
case SCALAR_T:
if (!isConstInScalar(arg, indexTypeSym))
typeErr = 1;
break;
case SUBRANGE_T:
if (!areSameType(
getSubrangeBaseTypeSym(indexTypeSym),
getTypeSym(arg))) typeErr = 1;
break;
default:
if (!areSameType(indexTypeSym,
getTypeSym(arg))) typeErr = 1;
break;
}
if (typeErr) {
errMsg = customErrorString("Invalid array "
"subscript. Expected type %s "
"but got %s",
typeToString(getType(indexTypeSym)),
typeToString(getType(arg)));
recordError(errMsg, yylineno, colno, SEMANTIC);
return NULL;
}
typeErr = 0;
arrayTypeSym = getArrayBaseSym(arrayTypeSym);
indexTypeSym = getArrayIndexSym(arrayTypeSym);
arg = arg->next;
}
/* Else are ready to return the base type */
if (arg) {
/* Didn't exhaust args, but exhausted arrays.
* Return arrayTypeSym */
recordError("Illegal array access -- too many indices.",
yylineno, colno, SEMANTIC);
return NULL;
}
returnTypeSym = newProxySymFromSym(arrayTypeSym);
returnTypeSym->isAddress = 1;
return returnTypeSym;
}
/*
* Returns the dimension of the given array (assumes that the given
* Symbol describing the array is the "first dimensional array")
*/
int getArrayDim(Symbol *s)
{
Symbol *nextIndexSym = NULL;
int dim = 0;
nextIndexSym = getArrayIndexSym(s);
while (nextIndexSym != NULL) {
dim++;
nextIndexSym = getArrayIndexSym(nextIndexSym);
}
return dim;
}
/*
* Returns the symbol which indexes the array.
*/
Symbol *getArrayIndexSym(Symbol *s)
{
if (!s) return NULL;
if (getType(s) != ARRAY_T) return NULL;
return getTypePtr(s)->Array->indexTypeSym;
}
Symbol *getArrayTerminalTypeSym(Symbol *s)
{
Symbol *baseSym = NULL;
if (!s) return NULL;
if (getType(s) != ARRAY_T) return NULL;
baseSym = getTypePtr(s)->Array->baseTypeSym;
while (getType(baseSym) == ARRAY_T) {
baseSym = getTypePtr(baseSym)->Array->baseTypeSym;
}
return baseSym;
}
Symbol *getArrayBaseSym(Symbol *s)
{
if (!s) return NULL;
if (getType(s) != ARRAY_T) return NULL;
return getTypePtr(getTypeSym((s)))->Array->baseTypeSym;
}
/*
* Returns the length of the given array symbol.
* Parameters
* s : a symbol with type == ARRAY_T whose length is to be
* calculated
*/
int getArrayLength(Symbol *s)
{
return (getArrayHighIndexValue(s) - getArrayLowIndexValue(s))+1;
}
/*
* Returns the upper bound on the index value of the given array symbol.
* Parameters
* arrayType : a symbol with type == ARRAY_T whose index upper
* upper bound is to be calculated
*/
int getArrayHighIndexValue(Symbol *arrayType)
{
Symbol *indexType = NULL;
indexType = getTypePtr(arrayType)->Array->indexTypeSym;
if (getType(indexType) == SUBRANGE_T) {
return getTypePtr(indexType)->Subrange->high;
} else return ((getTypePtr(indexType)->Scalar->consts->nElements) - 1);
}
/*
* Returns the lower bound on the index value of the given array symbol.
* Parameters
* arrayType : a symbol with type == ARRAY_T whose index upper
* lower bound is to be calculated
*/
int getArrayLowIndexValue(Symbol *arrayType)
{
Symbol *indexType = NULL;
if (!arrayType) {
fprintf(stderr, "Trying to get low index value of a NULL symbol"
".\n");
exit(1);
}
if (getType(arrayType) != ARRAY_T) {
fprintf(stderr, "Trying to low index value of a symbol which is"
" not an array\n");
exit(1);
}
indexType = getTypePtr(arrayType)->Array->indexTypeSym;
if (getType(indexType) == SUBRANGE_T) {
return getTypePtr(indexType)->Subrange->low;
} else return 0; /* else, indexed by scalar list, low val = 0 */
}
| C | CL | c5acec729de0197e5f16238d46adfef67b44f5db671ad62c6eaa21605d7fd24d |
/*
=================================================================================
T O P L E V E L M O D E M U X (TLMM)
H A R D W A R E A B S T R A C T I O N L A Y E R
FILE: HALtlmmModem.c
DESCRIPTION:
This module contains Modem processor-specific definitions.
=================================================================================
Edit History
$Header: //source/qcom/qct/core/systemdrivers/hal/tlmm/main/latest/src/7600/HALtlmmModem.c#3 $
when who what, where, why
-------- --- --------------------------------------------------------------
11-27-07 gfr Use HAL HW for HWIO.
08/27/07 dcf Created.
=================================================================================
Copyright (c) 2007 QUALCOMM Incorporated.
All Rights Reserved.
QUALCOMM Proprietary/GTDR
=================================================================================
*/
/*===============================================================================
INCLUDE FILES FOR MODULE
===============================================================================*/
#include <HALcomdef.h>
#include <HALhwio.h>
#include <HALhwioTLMMModem.h>
#include "HALtlmm.h"
#include "HALtlmmi7600.h"
/*===============================================================================
Buffer to save the values in the GPIO_OWNER_n register.
-----------------------------------------------------------------------------*/
uint32 HAL_tlmm_OwnerSaveBuff[HAL_TLMM_NUM_REG_GROUP] =
{
NULL, NULL, NULL, NULL, NULL, NULL,
};
/*===============================================================================
This array may need to be updated for each new target. The
elements in this array are the GPIO numbers that are assigned
to the KEYSENSE_CFG register. The values depend only on the
register setting. The numbers correspond to the GPIO positions
inside the register.
----------------------------------------------------------------------------*/
#define HAL_NUM_KEYSENSE 8
static const uint8 keysense[HAL_NUM_KEYSENSE] =
{ 42, 41, 40, 39, 38, 37, 36, 35 };
/*===============================================================================
GPIOn_PAGE and GPIOn_CFG registers are defined in the following array types.
This allows easy modifications if ever these registers change.
-----------------------------------------------------------------------------*/
/*===============================================================================
This array is used to provide the index to the gaPageCfgAddr array.
Each index corresponds to a GPIO register and is indexed by the
corresponding GPIO group number extracted in the HAL_tlmm_Info array.
-----------------------------------------------------------------------------*/
uint8 HAL_tlmm_GpioPCIdx[HAL_TLMM_NUM_REG_GROUP] = {0,1,0,0,0,0};
/* ==============================================================================
The following definition is used to construct the configuration mask to
write to the corresponding config and page registers. The HAL needs to
know the driver BSP encoding for this information and what each bit value
represents; however, it is not necessary that the BSP know this. The macros
that are contained in HAL_GPIO_CONFIG_MASK will need to be updated to reflect
the semantics of the configurations.
----------------------------------------------------------------------------*/
#define HAL_GPIO_CONFIG_MASK(cfg) \
((HAL_FUNC_VAL(cfg) << HWIO_GPIO1_CFG_FUNC_SEL_SHFT) | \
(HAL_PULL_VAL(cfg) << HWIO_GPIO1_CFG_GPIO_PULL_SHFT ) | \
(HAL_DRVSTR_VAL(cfg) << HWIO_GPIO1_CFG_DRV_STRENGTH_SHFT))
/*===============================================================================
FUNCTION
void HAL_tlmm_WriteRegister( HAL_tlmm_RegType reg,
uint32 mask,
uint8 nGroup,
uint32 value )
DESCRIPTION
This function outputs the value to the specified register based on the
HAL_tlmm_RegType parameter .
This function is to be used by the TLMM HAL module only! It should not
be used by the TLMM driver nor any other external module.
DEPENDENCIES
None.
RETURN VALUE
None.
SIDE EFFECTS
None.
===============================================================================*/
void HAL_tlmm_WriteRegister(HAL_tlmm_RegType reg,
uint32 nGroup,
uint32 mask,
uint32 value)
{
switch(reg)
{
case HAL_REG_OUT:
{
switch(nGroup)
{
case 0:
HWIO_OUTM(GPIO_OUT_0, mask, value);
break;
case 1:
HWIO_OUTM(GPIO_OUT_1, mask, value);
break;
case 2:
HWIO_OUTM(GPIO_OUT_2, mask, value);
break;
case 3:
HWIO_OUTM(GPIO_OUT_3, mask, value);
break;
case 4:
HWIO_OUTM(GPIO_OUT_4, mask, value);
break;
case 5:
HWIO_OUTM(GPIO_OUT_5, mask, value);
break;
default:
break;
}
break;
}
case HAL_REG_OE:
{
switch(nGroup)
{
case 0:
HWIO_OUTM(GPIO_OE_0, mask, value);
break;
case 1:
HWIO_OUTM(GPIO_OE_1, mask, value);
break;
case 2:
HWIO_OUTM(GPIO_OE_2, mask, value);
break;
case 3:
HWIO_OUTM(GPIO_OE_3, mask, value);
break;
case 4:
HWIO_OUTM(GPIO_OE_4, mask, value);
break;
case 5:
HWIO_OUTM(GPIO_OE_5, mask, value);
break;
default:
break;
}
break;
}
}
}
/*===============================================================================
FUNCTION
void HAL_tlmm_ReadRegister( HAL_tlmm_RegType reg, uint32 mask, uint8 nGroup )
DESCRIPTION
This function returns the value read at the specified location in the
specified register.
This function is to be used by the TLMM HAL module only! It should not
be used by the TLMM driver nor any other external module.
DEPENDENCIES
None.
RETURN VALUE
None.
SIDE EFFECTS
None.
===============================================================================*/
dword HAL_tlmm_ReadRegister(HAL_tlmm_RegType reg, uint32 nGroup, uint32 mask)
{
dword ret_val = 0x0;
switch(reg)
{
case HAL_REG_OUT:
{
switch(nGroup)
{
case 0:
ret_val = HWIO_INM(GPIO_OUT_0, mask);
break;
case 1:
ret_val = HWIO_INM(GPIO_OUT_1, mask);
break;
case 2:
ret_val = HWIO_INM(GPIO_OUT_2, mask);
break;
case 3:
ret_val = HWIO_INM(GPIO_OUT_3, mask);
break;
case 4:
ret_val = HWIO_INM(GPIO_OUT_4, mask);
break;
case 5:
ret_val = HWIO_INM(GPIO_OUT_5, mask);
break;
default:
break;
}
break;
}
case HAL_REG_OE:
{
switch(nGroup)
{
case 0:
ret_val = HWIO_INM(GPIO_OE_0, mask);
break;
case 1:
ret_val = HWIO_INM(GPIO_OE_1, mask);
break;
case 2:
ret_val = HWIO_INM(GPIO_OE_2, mask);
break;
case 3:
ret_val = HWIO_INM(GPIO_OE_3, mask);
break;
case 4:
ret_val = HWIO_INM(GPIO_OE_4, mask);
break;
case 5:
ret_val = HWIO_INM(GPIO_OE_5, mask);
break;
default:
break;
}
break;
}
case HAL_REG_IN:
{
switch(nGroup)
{
case 0:
ret_val = HWIO_INM(GPIO_IN_0, mask);
break;
case 1:
ret_val = HWIO_INM(GPIO_IN_1, mask);
break;
case 2:
ret_val = HWIO_INM(GPIO_IN_2, mask);
break;
case 3:
ret_val = HWIO_INM(GPIO_IN_3, mask);
break;
case 4:
ret_val = HWIO_INM(GPIO_IN_4, mask);
break;
case 5:
ret_val = HWIO_INM(GPIO_IN_5, mask);
break;
default:
break;
}
break;
}
}
return(ret_val);
}
/*===============================================================================
FUNCTION
void HAL_tlmm_InitProcSpec ( void )
DESCRIPTION
Performs any modem processor-specific initialization called from
HAL_tlmm_Init.
DEPENDENCIES
None.
RETURN VALUE
None.
SIDE EFFECTS
None.
===============================================================================*/
void HAL_tlmm_InitProcSpec( void )
{
/* Nothing to do here now. */
} /* END HAL_tlmm_InitProcSpec */
/*===============================================================================
FUNCTION
void HAL_tlmm_WriteOwnerRegister ( void )
DESCRIPTION
Writes the specified value to the GPIO_OWNER_n register, based on the
supplied mask.
DEPENDENCIES
None.
RETURN VALUE
None.
SIDE EFFECTS
None.
===============================================================================*/
void HAL_tlmm_WriteOwnerRegister( uint32 nGroup, uint32 mask, uint32 value )
{
switch(nGroup)
{
case 0:
HWIO_OUTM(GPIO_OWNER_0, mask, value);
break;
case 1:
HWIO_OUTM(GPIO_OWNER_1, mask, value);
break;
case 2:
HWIO_OUTM(GPIO_OWNER_2, mask, value);
break;
case 3:
HWIO_OUTM(GPIO_OWNER_3, mask, value);
break;
case 4:
HWIO_OUTM(GPIO_OWNER_4, mask, value);
break;
case 5:
HWIO_OUTM(GPIO_OWNER_5, mask, value);
break;
default:
break;
}
}
/*===============================================================================
FUNCTION
void HAL_tlmm_ReadOwnerRegister ( void )
DESCRIPTION
Reads the specified value from the GPIO_OWNER_n register, based on the
supplied mask.
DEPENDENCIES
None.
RETURN VALUE
None.
SIDE EFFECTS
None.
===============================================================================*/
void HAL_tlmm_ReadOwnerRegister( uint32 nGroup, uint32 mask )
{
switch(nGroup)
{
case 0:
HWIO_INM(GPIO_OWNER_0, mask);
break;
case 1:
HWIO_INM(GPIO_OWNER_1, mask);
break;
case 2:
HWIO_INM(GPIO_OWNER_2, mask);
break;
case 3:
HWIO_INM(GPIO_OWNER_3, mask);
break;
case 4:
HWIO_INM(GPIO_OWNER_4, mask);
break;
case 5:
HWIO_INM(GPIO_OWNER_5, mask);
break;
default:
break;
}
}
/*=========================================================================
FUNCTION
void HAL_tlmm_SetPort(HAL_tlmm_PortType ePort, uint32 mask, uint32 value)
DESCRIPTION
Selects the specified port if it is defined.
PARAMETERS
ePort - The requested port to configure.
mask - The mask to use for this port.
value - The value to be written to the port.
DEPENDENCIES
None.
RETURN VALUE
None.
SIDE EFFECTS
None.
=========================================================================*/
void HAL_tlmm_SetPort(HAL_tlmm_PortType ePort, uint32 mask, uint32 value)
{
switch(ePort)
{
case HAL_TLMM_USB_PORT_SEL:
HWIO_OUTM(USB_PIN_SEL, mask, value);
break;
case HAL_TLMM_PORT_CONFIG_USB:
HWIO_OUTM(USB_PIN_CONFIG, mask, value);
break;
case HAL_TLMM_PORT_TSIF:
HWIO_OUTM(TSIF_PORT_CFG, mask, value);
break;
case HAL_TLMM_AUD_PCM:
break;
case HAL_TLMM_UART1:
break;
case HAL_TLMM_UART3:
break;
default:
break;
}
}
/*===============================================================================
Register changes for this target should be contained in the above structures
and functions to shorten porting time.
=============================================================================*/
/*===============================================================================
FUNCTION
HAL_tlmm_SetOwner( uint16 nWhichGpio, uint8 nWhichOwner )
DESCRIPTION
Programs the GPIO_OWNER register to the processor specified in the
parameter.
PARAMETERS
nWhichConfig - The masked configuration containing the GPIO number to set.
nWhichOwner - The owner processor to set the GPIO ownership to.
DEPENDENCIES
None.
RETURN VALUE
None.
SIDE EFFECTS
None.
===============================================================================*/
void HAL_tlmm_SetOwner(uint16 nWhichGpio, uint8 nWhichOwner)
{
uint32 nGroup;
uint32 nGpioOffset;
uint32 nMask = 0;
uint32 nValue = 0;
if( nWhichGpio >= HAL_TLMM_NUM_GPIO )
{
return;
}
nGroup = (uint32)HAL_GET_GROUP(nWhichGpio);
nGpioOffset = (nWhichGpio - HAL_tlmm_GroupStart[nGroup]);
nMask = (1UL << nGpioOffset);
switch(nWhichOwner)
{
case HAL_TLMM_OWNER_CLIENT:
HAL_tlmm_OwnerSaveBuff[nGroup] |= (1UL << nGpioOffset);
nValue = nMask;
break;
case HAL_TLMM_OWNER_MASTER:
HAL_tlmm_OwnerSaveBuff[nGroup] &= ~(1UL << nGpioOffset);
nValue = 0x0;
break;
default:
return;
}
HAL_tlmm_WriteOwnerRegister(nGroup, nMask, nValue);
}
/*===============================================================================
FUNCTION
void HAL_tlmm_SetOwnerGroup(const uint16 nWhichGroup[],
uint16 nWhatSize,
uint8 nWhichOwner)
DESCRIPTION
Programs the GPIO_OWNER register to the processor specified in the
parameter.
PARAMETERS
nWhichGroup[] - A array of GPIO configurations which includes GPIO number.
nWhatSize - The size of the array to configure.
nWhichOwner - The owner to set the group of GPIOs to.
DEPENDENCIES
None.
RETURN VALUE
None.
SIDE EFFECTS
None.
===============================================================================*/
void HAL_tlmm_SetOwnerGroup(const uint32 nWhichGroupSet[],
uint16 nWhatSize,
uint8 nWhichOwner)
{
uint32 nIdx;
uint32 nGpioNumber;
uint32 nGpioOffset;
uint32 nGroup;
uint32 nMask[HAL_TLMM_NUM_REG_GROUP];
uint32 nBuffer[HAL_TLMM_NUM_REG_GROUP];
for(nIdx = 0; nIdx < HAL_TLMM_NUM_REG_GROUP; ++nIdx)
{
nMask[nIdx] = 0x0;
nBuffer[nIdx] = 0x0;
}
switch(nWhichOwner)
{
case HAL_TLMM_OWNER_CLIENT:
for( nIdx = 0; nIdx < nWhatSize; nIdx++ )
{
nGpioNumber = HAL_GPIO_NUMBER(nWhichGroupSet[nIdx]);
if( nGpioNumber >= HAL_TLMM_NUM_GPIO )
{
return;
}
nGroup = HAL_GET_GROUP(nGpioNumber);
nGpioOffset = (nGpioNumber - HAL_tlmm_GroupStart[nGroup]);
/* Save the OWNER value. */
HAL_tlmm_OwnerSaveBuff[nGroup] |= (1UL << nGpioOffset);
/* Set the mask. */
nMask[nGroup] |= (1UL << nGpioOffset);
nBuffer[nGroup] |= (1UL << nGpioOffset);
}
break;
case HAL_TLMM_OWNER_MASTER:
for( nIdx = 0; nIdx < nWhatSize; nIdx++ )
{
nGpioNumber =(uint32)HAL_GPIO_NUMBER(nWhichGroupSet[nIdx]);
if( nGpioNumber >= HAL_TLMM_NUM_GPIO )
{
return;
}
nGroup = HAL_GET_GROUP(nGpioNumber);
nGpioOffset = (nGpioNumber - HAL_tlmm_GroupStart[nGroup]);
/* Save the OWNER value. */
HAL_tlmm_OwnerSaveBuff[nGroup] &= ~(1UL << nGpioOffset);
/* Set the mask. */
nMask[nGroup] |= (1UL << nGpioOffset);
nBuffer[nGroup] &= ~(1UL << nGpioOffset);
}
break;
default:
return;
}
for( nIdx = 0; nIdx < HAL_TLMM_NUM_REG_GROUP; ++nIdx )
{
HAL_tlmm_WriteOwnerRegister(nIdx, nMask[nIdx], nBuffer[nIdx]);
}
}
/*===============================================================================
FUNCTION
void HAL_tlmm_WriteConfig( uint16 nGpioNumber, uint16 nConfig )
DESCRIPTION
Programs the GPIOn_PAGE and GPIOn_CFG registers based on the input
parameters. For APPS processor, this function is stubbed out.
PARAMETERS
nGpioNumber - GPIO number to configure
nGroup - The GPIOn_PAGE/CFG group that this GPIO belongs to
(defined as 0 for GPIO1_XXX, and 1 for GPIO2_XXX).
nConfig - The masked configuration for this GPIO.
NOTE: This function is for use by the TLMM HAL module only. It should not
exported to the driver. Driver has no knowledge of the nGroup
parameter.
DEPENDENCIES
None.
RETURN VALUE
None.
SIDE EFFECTS
None.
===============================================================================*/
void HAL_tlmm_WriteConfig( uint32 nGpioNumber, uint32 nGroup, uint32 nConfig )
{
/* Find out which registers we need to write. */
if ( HAL_tlmm_GpioPCIdx[nGroup] == 0 )
{
HWIO_OUT(GPIO1_PAGE,nGpioNumber);
HWIO_OUT(GPIO1_CFG, HAL_GPIO_CONFIG_MASK(nConfig));
}
else
{
HWIO_OUT(GPIO2_PAGE,nGpioNumber);
HWIO_OUT(GPIO2_CFG, HAL_GPIO_CONFIG_MASK(nConfig));
}
}
/*===============================================================================
FUNCTION
void HAL_tlmm_ConfigKeysense(const uint32 nKeysenseArr[],
uint16 nNumKeysense);
DESCRIPTION
Configures the Keysense register to the GPIOs specified in the driver
BSP.
PARAMETERS
nKeysenseArr[] - Array of GPIO configurations specified as KEYSENSE GPIOS.
nNumKeysense - Number of KEYSENSE GPIOs.
DEPENDENCIES
At this time, assumes keysense GPIOs are contained in one register.
RETURN VALUE
None.
SIDE EFFECTS
None.
===============================================================================*/
void HAL_tlmm_ConfigKeysense(const uint32 nKeysenseArr[], uint16 nNumKeysense)
{
uint32 nConfigMask = 0;
uint16 nWhichGpio;
uint16 keyCfgIdx;
uint16 keyGpio;
/* Loop through all combinations to match the GPIO numbers
above. */
for( keyGpio = 0; keyGpio < nNumKeysense; ++keyGpio )
{
for( keyCfgIdx = 0; keyCfgIdx < HAL_NUM_KEYSENSE; ++keyCfgIdx )
{
nWhichGpio = (uint16)HAL_GPIO_NUMBER(nKeysenseArr[keyGpio]);
/* OR in the bit at the KEYSENSE_CFG register position.*/
if(keysense[keyCfgIdx] == nWhichGpio)
{
nConfigMask |= (1UL << keyCfgIdx);
}
}
}
HWIO_OUT(KEYSENSE_CFG, nConfigMask);
}
/*=============================================================================*/
| C | CL | c7fb1709835e3dac45d8d48c3ee8b6e346c853e2637b2224a2dd877ba0f6f3c3 |
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class zime_media_ZIMEVideoClientJNI */
#ifndef _Included_zime_media_ZIMEVideoClientJNI
#define _Included_zime_media_ZIMEVideoClientJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: Create
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_Create
(JNIEnv *, jclass);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: Destroy
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_Destroy
(JNIEnv *, jclass);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: Init
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_Init
(JNIEnv *, jclass);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: Terminate
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_Terminate
(JNIEnv *, jclass);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: Exit
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_Exit
(JNIEnv *, jclass);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetLogLevel
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetLogLevel
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: CreateChannel
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_CreateChannel
(JNIEnv *, jclass, jboolean UsingEncodeCAllback, jint CodecType);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: DeleteChannel
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_DeleteChannel
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: MaxNumOfChannels
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_MaxNumOfChannels
(JNIEnv *, jclass);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetLocalReceiver
* Signature: (IIIIILzime/media/ZIMEVideoClientJNI/StrPtr;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetLocalReceiver
(JNIEnv *, jclass, jint, jint, jint, jint, jint, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetLocalReceiver
* Signature: (ILzime/media/ZIMEVideoClientJNI/IntPtr;Lzime/media/ZIMEVideoClientJNI/IntPtr;Lzime/media/ZIMEVideoClientJNI/IntPtr;Lzime/media/ZIMEVideoClientJNI/IntPtr;Lzime/media/ZIMEVideoClientJNI/StrPtr;I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetLocalReceiver
(JNIEnv *, jclass, jint, jobject, jobject, jobject, jobject, jobject, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetSendDestination
* Signature: (IIIIILzime/media/ZIMEVideoClientJNI/StrPtr;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetSendDestination
(JNIEnv *, jclass, jint, jint, jint, jint, jint, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetSendDestination
* Signature: (ILzime/media/ZIMEVideoClientJNI/StrPtr;ILzime/media/ZIMEVideoClientJNI/IntPtr;Lzime/media/ZIMEVideoClientJNI/IntPtr;Lzime/media/ZIMEVideoClientJNI/IntPtr;Lzime/media/ZIMEVideoClientJNI/IntPtr;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetSendDestination
(JNIEnv *, jclass, jint, jobject, jint, jobject, jobject, jobject, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: StartListen
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StartListen
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: StopListen
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StopListen
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: StartPlayout
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StartPlayout
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: StopPlayout
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StopPlayout
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: StartSend
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StartSend
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: StopSend
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StopSend
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetNumOfAudioCodecs
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetNumOfAudioCodecs
(JNIEnv *, jclass);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetNumOfVideoCodecs
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetNumOfVideoCodecs
(JNIEnv *, jclass);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetAudioCodec
* Signature: (ILzime/media/ZIMEVideoClientJNI/ZIMEAudioCodeInfo;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetAudioCodec
(JNIEnv *, jclass, jint, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetVideoCodec
* Signature: (ILzime/media/ZIMEVideoClientJNI/ZIMEVideoCodeInfo;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetVideoCodec
(JNIEnv *, jclass, jint, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetSendCodec
* Signature: (ILzime/media/ZIMEVideoClientJNI/ZIMEAudioCodeInfo;Lzime/media/ZIMEVideoClientJNI/ZIMEVideoCodeInfo;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetSendCodec
(JNIEnv *, jclass, jint, jobject, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetSendCodec
* Signature: (ILzime/media/ZIMEVideoClientJNI/ZIMEAudioCodeInfo;Lzime/media/ZIMEVideoClientJNI/ZIMEVideoCodeInfo;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetSendCodec
(JNIEnv *, jclass, jint, jobject, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetRecPayloadType
* Signature: (ILzime/media/ZIMEVideoClientJNI/ZIMEAudioCodeInfo;Lzime/media/ZIMEVideoClientJNI/ZIMEVideoCodeInfo;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetRecPayloadType
(JNIEnv *, jclass, jint, jobject, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetRecCodec
* Signature: (ILzime/media/ZIMEVideoClientJNI/ZIMEAudioCodeInfo;Lzime/media/ZIMEVideoClientJNI/ZIMEVideoCodeInfo;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetRecCodec
(JNIEnv *, jclass, jint, jobject, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetSourceFilter
* Signature: (IIILzime/media/ZIMEVideoClientJNI/StrPtr;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetSourceFilter
(JNIEnv *, jclass, jint, jint, jint, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetSendSSRC
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetSendSSRC
(JNIEnv *, jclass, jint, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetSendSSRC
* Signature: (ILzime/media/ZIMEVideoClientJNI/IntPtr;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetSendSSRC
(JNIEnv *, jclass, jint, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetAGCStatus
* Signature: (ZI)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetAGCStatus
(JNIEnv *, jclass, jboolean, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetAGCStatus
* Signature: (Lzime/media/ZIMEVideoClientJNI/BoolPtr;Lzime/media/ZIMEVideoClientJNI/IntPtr;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetAGCStatus
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetECStatus
* Signature: (Z)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetECStatus
(JNIEnv *, jclass, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetECStatus
* Signature: (Lzime/media/ZIMEVideoClientJNI/BoolPtr;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetECStatus
(JNIEnv *, jclass, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetNSStatus
* Signature: (Z)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetNSStatus
(JNIEnv *, jclass, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: GetNSStatus
* Signature: (Lzime/media/ZIMEVideoClientJNI/BoolPtr;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetNSStatus
(JNIEnv *, jclass, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetSpeakerMode
* Signature: (Z)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetSpeakerMode
(JNIEnv *, jclass, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetSampleRate
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetSampleRate
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetFECStatus
* Signature: (IZ)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetFECStatus
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetFECStatus
* Signature: (IZ)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetNACKStatus
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetIframeInterval
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetIframeInterval
(JNIEnv *, jclass, jint, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SendOneIFrame
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_ConfigVideoIntraFrameRefresh
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetCCE
* Signature: (IZ)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetCCE
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetDEE
* Signature: (IZ)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetDEE
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetDeBlock
* Signature: (IZ)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetDeBlock
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetBLE
* Signature: (IZ)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetBLE
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetDNO
* Signature: (IZ)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetDNO
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetVideoDisplayWnd
* Signature: (Ljava/lang/Object;Ljava/lang/Object;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVideoDisplayWnd
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetCallBack
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetCallBack
(JNIEnv *, jclass);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetVideoCallBack
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVideoCallBack
(JNIEnv *, jclass);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetVideoEncodeFun
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVideoEncodeFun(JNIEnv *env, jclass, jint i_s32ChId);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetVideoDecodeFun
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVideoDecodeFun(JNIEnv *env, jclass, jint i_s32ChId);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetCodecType
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVendorType
(JNIEnv *, jclass, jint, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetModeSubset
* Signature:
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetModeSubset
(JNIEnv *, jclass, jint, jbyteArray, jint, jboolean);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetLogPath
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetLogPath
(JNIEnv *, jclass, jstring);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetVideoDevCapSize
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVideoDevCapSize
(JNIEnv *, jclass, jint, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetVideoDevices
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVideoDevices
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetInputMute
* Signature: (IZ)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetInputMute
(JNIEnv *, jclass, jint, jboolean);
/*
* Class: zime_video_ZIMEVideoClientJNI
* Method: StartCapFileAsCamera
* Signature: (ILjava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StartCapFileAsCamera
(JNIEnv *, jclass, jint, jstring);
/*
* Class: zime_video_ZIMEVideoClientJNI
* Method: StopCapFileAsCamera
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StopCapFileAsCamera
(JNIEnv *, jclass, jint);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetNetworkQualityNotify
(JNIEnv *, jclass, jint);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetActivity
(JNIEnv *, jclass, jobject);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetCapaBilityType
* Signature: (IZ)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetCapaBilitySet
(JNIEnv *, jclass, jint, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: DisconnectDevice
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_DisconnectDevice
(JNIEnv *, jclass, jint, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: ConnectDevice
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_ConnectDevice
(JNIEnv *, jclass, jint, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetVQEScene
* Signature: (Z)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVQEScene
(JNIEnv *, jclass, jint);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetSendDTMFPayloadType
* Signature: (I/B)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetSendDTMFPayloadType
(JNIEnv *, jclass, jint i_s32ChId, jbyte i_u8PT);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SendDTMF
* Signature: (I/B/I/I)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SendDTMF
(JNIEnv *, jclass, jint i_s32ChId, jint i_s32EvtNum, jboolean i_bOutBand,
jint i_s32LenMs = 160, jint i_s32Level = 10);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetDTMFFeedbackStatus
* Signature: (B/B)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetDTMFFeedbackStatus
(JNIEnv *, jclass, jboolean i_bEnable, jboolean i_bDirectFeedback = false);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetAudioQosStat
(JNIEnv *, jclass, jint i_s32ChId, jobject, jobject);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_GetVideoQosStat
(JNIEnv *, jclass, jint i_s32ChId, jobject, jobject);
// 外部收发相关的接口 前三个接口为start时调用
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetExternalTransport
(JNIEnv *env, jclass, jint i_s32ChId, jint i_s32LocalRTPPort, jobject jPeerAddr, jint i_s32PeerRTPPort, jboolean i_bIsHaveVideo);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StartRTPExternalTransport
(JNIEnv *, jclass, jboolean i_bIsStartAudio, jboolean i_bIsStartVideo);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StartRTCPExternalTransport
(JNIEnv *, jclass, jboolean i_bIsStartAudio, jboolean i_bIsStartVideo);
// 最后退出通话调用
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StopExternalTransportRecv
(JNIEnv *, jclass);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StopExternalTransportSend
(JNIEnv *, jclass);
// 音视频互转接口
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_ToAudio( JNIEnv *, jclass, jint ChId);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_ToAudioAndVideo(JNIEnv *env, jclass, jint ChId,jint i_s32LocalRTPPort, jint i_s32PeerRTPPort, jobject jPeerAddr);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_StartAudio(JNIEnv *env, jclass, jint ChId);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVideoQualityLevelSet
(JNIEnv *pEnv, jclass, int i_s32ChId, int nNum, jobjectArray jlevels_array);
/*
* Class: zime_media_ZIMEVideoClientJNI
* Method: SetSynchronization
* Signature: (IZ)I
*/
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetSynchronization
(JNIEnv *, jclass, jint, jboolean);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVideoEncoderAbility
(JNIEnv *env, jclass, int i_s32ChId, int i_s32NaluNum, int i_s32EncodeProfile);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetLogCallBack
(JNIEnv *env, jclass);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_LogExit
(JNIEnv *env, jclass);
JNIEXPORT jint JNICALL Java_zime_media_ZIMEVideoClientJNI_SetVideoModeSet
(JNIEnv *env, jclass);
#ifdef __cplusplus
}
#endif
#endif
| C | CL | 7af21c6650e5dd5a395737cfe15daca36b1d538111c8338d1389be2071fc737c |
/*
// Dao Graphics Engine
// http://www.daovm.net
//
// Copyright (c) 2013, Limin Fu
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
// OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __DAO_PAINTER_H__
#define __DAO_PAINTER_H__
#include "dao_canvas.h"
#include "dao_opengl.h"
typedef struct DaoxPainter DaoxPainter;
/*
// Polygons converted from the stroking and filling areas of the item.
//
// These polygons are potentially overlapping, due to the fact that
// this frontend needs to be light and efficient, so that it can take
// the advantage of hardware acceleration.
//
// They should be filled using stencil buffer or other techniques to
// avoid multiple drawing in the overlapping areas.
//
// Note: two-point polygons are used to represent rectangles by pairs
// of points (left,bottom) and (right,top).
*/
struct DaoxPainter
{
DAO_CSTRUCT_COMMON;
DaoxOBBox2D obbox;
DaoxVector3D campos;
DaoxShader shader;
DaoxBuffer buffer;
};
extern DaoType *daox_type_painter;
DaoxPainter* DaoxPainter_New();
void DaoxPainter_Delete( DaoxPainter *self );
void DaoxPainter_InitShaders( DaoxPainter *self );
void DaoxPainter_InitBuffers( DaoxPainter *self );
void DaoxPainter_Paint( DaoxPainter *self, DaoxCanvas *canvas, DaoxAABBox2D viewport );
void DaoxPainter_PaintCanvasImage( DaoxPainter *self, DaoxCanvas *canvas, DaoxAABBox2D viewport, DaoxImage *image, int width, int height );
#endif
| C | CL | eb7146242b14dc47fafdd7b1365dacc238fa9dade62781a7a9005e1552f04c14 |
// Fimbulwinter
// John Shedletsky
//
// For up to date Fimbulwinter info, see:
// http://www.stanford.edu/~jjshed/chess
#define BUILD_DATE "November 29, 2002"
#define VERSION "5.00"
#define INI_FILENAME "fimbulwinter_5_00.ini"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <signal.h>
#include <windows.h>
#include <windowsx.h>
#include <mmsystem.h>
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <math.h>
#include <io.h>
#include <fcntl.h>
#include "defs.h"
#include "data.h"
#include "protos.h"
#include "stats.h"
#include "book.h"
void main()
{
static char s[256];
static char args[3][256];
char pgn_trans[8];
int from, to, bits,i;
BOOL found;
int computer_side = NO_COLOR;
move CompMove;
printf("\n");
printf("FIMBULWINTER\n");
printf("------------\n");
printf("Version %s\n", VERSION);
printf("%s Build\n", BUILD_DATE);
printf("Copyright 2002 John Shedletsky\n");
printf("[email protected]\n");
printf("Fimbulwinter Homepage:\nhttp://www.stanford.edu/~jjshed/chess\n");
printf("\nType help for commands\n");
printf("\n");
Init();
for(;;)
{
if (side == computer_side) { /* computer's turn */
if(GameStateCheck()) { // see if game is over
ReInit(TRUE);
computer_side = NO_COLOR;
}
Think(CONSOLE);
if (pv[0][0].id == 0) {
printf("(no legal moves)\n");
computer_side = NO_COLOR;
continue;
}
CompMove = pv[0][0];
printf("Computer's move: %s\n", MoveStr(CompMove));
MakeMove(CompMove);
ply = 0;
if(GameStateCheck()) { // see if game is over
ReInit(TRUE);
computer_side = NO_COLOR;
}
continue;
}
/* get user input */
printf("Fimbulwinter> ");
scanf("%s", s);
if(!strcmp(s, "on")) {
computer_side = side;
continue;
}
if(!strcmp(s, "off")) {
computer_side = NO_COLOR;
continue;
}
if(!strcmp(s, "zobrist")) {
// spit out this position's zobrist hash key
printf("\nZobrist key: %I64u\n", ZobristKey());
continue;
}
if(!strcmp(s, "ttstats")) {
StatsDump_TTable();
continue;
}
if(!strcmp(s, "clearstats")) {
ClearOnePlyStats();
continue;
}
if(!strcmp(s, "cleartable")) {
ClearTTable();
continue;
}
if(!strcmp(s, "cross")) {
TTableCrossSection();
continue;
}
if(!strncmp(s, "load", 4)) {
printf("FEN position file: ");
scanf("%s", args[0]);
if(!LoadFEN(args[0])) printf("\n\nFile Error!\n\n");
continue;
}
if (!strcmp(s, "exit")) {
return;
}
if (!strcmp(s, "d")) {
DrawBoard();
continue;
}
if (!strcmp(s, "bench")) {
TSCP_Bench();
continue;
}
if (!strcmp(s, "new")) {
ReInit(TRUE);
continue;
}
if (!strcmp(s, "eval")) {
printf("Assessment: %i\n", EvaluateBoard());
continue;
}
if (!strcmp(s, "pawneval")) {
BuildPawnLists();
printf("Pawn structure assessment: %i\n", PawnEval(side));
continue;
}
if (!strcmp(s, "safe")) {
printf("King safety assessment: %i\n", KingSafety(side));
continue;
}
if (!strcmp(s, "movegen")) { //generate and list current possible moves
GenerateMoves();
ListPossibleMoves(FALSE);
continue;
}
if (!strcmp(s, "legalgen")) { // generates and lists all legal moves
GenerateMoves();
ListPossibleMoves(TRUE);
continue;
}
if (!strcmp(s, "clear")) { // clear board
ReInit(TRUE);
ClearBoard();
continue;
}
if (!strcmp(s, "nocastle")) { // sets castle flags to null
castle = 0;
continue;
}
if (!strcmp(s, "xboard")) {
xboard();
exit(0);
}
if (strpbrk( s, "@" )) { // put piece
ParsePutPiece(s);
continue;
}
if (!strcmp(s, "undo")) { // go back one ply
UnmakeMove();
continue;
}
if (!strcmp(s, "makebookpgn")) { // make opening book from PGN
printf("\nInput: ");
scanf("%s", args[0]);
printf("\nOutput: ");
scanf("%s", args[1]);
printf("\nExtract to ply: ");
scanf("%i", (int *)args[2]);
if(MakeBookFromPGN(args[0], args[1], *(int *)args[2])) { // <- Convoluted typecast
printf("\nFinished!\n\n");
} else {
printf("\nError in compilation!\n\n");
}
continue;
}
if (!strcmp(s, "help")) { // show help
printf("\nFIMBULWINTER HELP\n");
printf("-----------------\n");
printf("Note: this is only a partial list. See source for advanced options.\n\n");
printf("Command Function\n");
printf("new Start new game\n");
printf("d Display board\n");
printf("on\\off Toggle computer player\n");
printf("clear Clears board\n");
printf("nocastle Voids castle permissions\n");
printf("undo Takes back last move\n");
printf("bench Loads benchmark position\n");
printf("load Loads a FEN position\n");
printf("exit Quits program\n");
printf("\n");
printf("Moves are entered in co-ordinant notation\n\n");
printf("Example Move Effect\n");
printf("d2d4 Move piece at d2 to d4\n");
printf("e1g1 Kingside castle for white\n");
printf("e7e8r Pawn promote to rook\n");
printf("P@d4 Puts a white pawn at d4\n\n");
continue;
}
if(!IsCoordNotationMove(s)) {
PGNtoCoordMove(s, pgn_trans);
memcpy(s, pgn_trans, PGN_MOVE_LEN);
}
// else try to see if it's a legal move
from = (s[0] - 'a')+(8*(s[1]-'1'));
to = (s[2] - 'a')+(8*(s[3]-'1'));
bits = 0;
ply = 0;
found = FALSE;
GenerateMoves();
for(i = 0; i < ms_end[0]; i++) {
if(movestack[i].m.info.from == from && movestack[i].m.info.to == to) {
found = TRUE;
// read promotion choice
if(movestack[i].m.info.bits & SM_PROMOTE) {
switch(s[4]) {
case 'n':
break;
case 'b':
i+=1;
break;
case 'r':
i+=2;
break;
default:
i+=3;
break;
}
}
break;
}
}
if (found) {
if (!MakeMove(movestack[i].m)) {
printf("That move would leave your king in check!\n");
} else {
ply=0;
if(GameStateCheck()) { // see if game is over
ReInit(TRUE);
computer_side = NO_COLOR;
}
}
} else {
printf("Illegal Move\n");
}
}
}
void Init()
{
// Read engine constants
ReadINIFile(INI_FILENAME);
// Register critical callback functions to clean up memory before we exit
atexit(TTableCleanup);
atexit(BookCleanup);
// Setup memory allocation
TTableInit();
InitBook();
side = WHITE; // Inited here because important for zkey generation
xside = BLACK;
enpassant = NO_EP_SQR;
castle = CASTLE_WHITEKINGSIDE | CASTLE_WHITEQUEENSIDE | CASTLE_BLACKKINGSIDE | CASTLE_BLACKQUEENSIDE;
// Only called once, when the program starts
InitRays();
InitZobristKeys(); // seeds random number generator to fixed value
ReInit(TRUE);
LoadBook(INI_BOOK_FILE);
srand((unsigned int)GetTickCount());
}
void ReInit(BOOL clear_hash_table)
{
// Called to reset board state to init
//
// clear_hash_table is usually set to TRUE, except when compiling an opening book,
// where the transposition table is not being used, but calling ClearTTable() is
// an incredible performace bottleneck (profiler says about 90% the time spent
// parsing games is spent clearing the hash table!). Which is kind of believable,
// given that it can be around 64 MB or larger.
InitBoard();
if(clear_hash_table == TRUE) ClearTTable();
side = WHITE;
xside = BLACK;
computer_side = NO_COLOR;
ply = 0;
hply = 0;
castle = CASTLE_WHITEKINGSIDE | CASTLE_WHITEQUEENSIDE | CASTLE_BLACKKINGSIDE | CASTLE_BLACKQUEENSIDE;
enpassant = NO_EP_SQR;
board_key = ZobristKey();
}
void ParsePutPiece(char *s)
{
// format: "put B@a3 - white bishop at a3
char piece = EMPTY;
char color;
if(s[0] >= 'a') { color = BLACK; } else { color = WHITE; }
if(s[0] >= 'a') s[0]-=32;
if(s[0] == 'P') piece = PAWN;
if(s[0] == 'B') piece = BISHOP;
if(s[0] == 'N') piece = KNIGHT;
if(s[0] == 'R') piece = ROOK;
if(s[0] == 'Q') piece = QUEEN;
if(s[0] == 'K') piece = KING;
if (piece == EMPTY) {
printf("Invalid syntax\n");
return;
}
BOARD((s[2]-'a'),(s[3]-'1')).piece = piece;
BOARD((s[2]-'a'),(s[3]-'1')).color = color;
}
void ClearBoard()
{
int i;
for(i = 0; i < 64; i++) {
board[i].color = NO_COLOR;
board[i].piece = EMPTY;
}
}
void DrawBoard()
{
// ascii for 'a' is = 'A'+32
// Black in lower case
int x,y,c;
printf("\n\n");
for(y = 7; y >= 0; y--) {
printf("\t%d ", y+1);
for(x = 0; x < 8; x++) {
if(BOARD(x,y).color == BLACK) { c = 1; } else { c = 0; }
printf("%c ", piece_char[BOARD(x,y).piece] + (c*32));
}
printf("\n");
}
printf("\n\t a b c d e f g h\n");
printf("\n\n");
}
char *MoveStr(move Move)
{
static char str[6];
// regular move
str[0] = (Move.info.from%8)+'a';
str[1] = (Move.info.from/8)+'1';
str[2] = (Move.info.to%8)+'a';
str[3] = (Move.info.to/8)+'1';
if(Move.info.bits & SM_PROMOTE) {
str[4] = piece_char[Move.info.promote]+32;
str[5] = '\0';
return str;
}
str[4] = '\0';
return str;
}
BOOL GameStateCheck()
{
// checks to see if the game is over and prints the result
int i;
ply = 0;
GenerateMoves();
// check for a legal move
for(i = 0; i < ms_end[0]; ++i) {
if(MakeMove(movestack[i].m)) {
UnmakeMove();
return FALSE;
}
}
if(i == ms_end[0]) {
if(InCheck(side)) {
if(side == WHITE)
printf("0-1 {-Black mates-}\n");
else
printf("1-0 {-White mates-}\n");
} else {
printf("1/2-1/2 {-Stalemate-}\n");
}
return TRUE;
} else {
if (CountRepetitions() == 3) {
printf("1/2-1/2 {Draw by repetition}\n");
return TRUE;
}
if (fifty >= 100) {
printf("1/2-1/2 {Draw by fifty move rule}\n");
return TRUE;
}
}
return FALSE;
}
void ListPossibleMoves(BOOL verify)
{
// prints all moves possible in current position
// if verify is true, makes sure that all of them are legal
int i, count;
ply = 0;
printf("\nPossible Moves:\n");
count = 0;
for (i = ms_begin[0]; i < ms_end[0]; i++) {
if(verify == TRUE) {
if(MakeMove(movestack[i].m)) {
UnmakeMove();
printf("%s ",MoveStr(movestack[i].m));
count++;
}
} else {
printf("%s ",MoveStr(movestack[i].m));
count++;
}
}
printf("\nTotal Moves: %i\n\n", count);
}
/* bench: This is a little benchmark code that calculates how many
nodes per second TSCP searches.
It sets the position to move 17 of Bobby Fischer vs. J. Sherwin,
New Jersey State Open Championship, 9/2/1957.
Then it searches five ply three times. It calculates nodes per
second from the best time. */
/* I'm including the same benchmark position as Tom Kerrigan did to
facilitate relative performance assessments. I'm planning to add
other bench marks later
*/
void TSCP_Bench()
{
int i;
int bench_color[64] = {
2, 1, 1, 2, 2, 1, 1, 2,
1, 2, 2, 2, 2, 1, 1, 1,
2, 1, 2, 1, 1, 2, 1, 2,
2, 2, 2, 1, 2, 2, 0, 2,
2, 2, 1, 0, 2, 2, 2, 2,
2, 2, 0, 2, 2, 2, 0, 2,
0, 0, 0, 2, 2, 0, 0, 0,
0, 2, 0, 2, 0, 2, 0, 2
};
int bench_piece[64] = {
0, 4, 3, 0, 0, 4, 6, 0,
1, 0, 0, 0, 0, 1, 1, 1,
0, 1, 0, 5, 1, 0, 2, 0,
0, 0, 0, 2, 0, 0, 2, 0,
0, 0, 1, 1, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0,
1, 1, 5, 0, 0, 1, 3, 1,
4, 0, 3, 0, 4, 0, 6, 0
};
int flip[64] = { // used to flip pos, since I use different board coords than Tom
56, 57, 58, 59, 60, 61, 62, 63,
48, 49, 50, 51, 52, 53, 54, 55,
40, 41, 42, 43, 44, 45, 46, 47,
32, 33, 34, 35, 36, 37, 38, 39,
24, 25, 26, 27, 28, 29, 30, 31,
16, 17, 18, 19, 20, 21, 22, 23,
8, 9, 10, 11, 12, 13, 14, 15,
0, 1, 2, 3, 4, 5, 6, 7
};
for (i = 0; i < 64; ++i) {
board[i].color = bench_color[flip[i]];
board[i].piece = bench_piece[flip[i]];
}
side = WHITE;
xside = BLACK;
castle = 0;
enpassant = NO_EP_SQR;
fifty = 0;
ply = 0;
hply = 20;
board_key = ZobristKey();
}
// xboard code largely borrowed from Tom Kerrigan
/* xboard() is a substitute for main() that is XBoard
and WinBoard compatible. See the following page for details:
http://www.research.digital.com/SRC/personal/mann/xboard/engine-intf.html */
void xboard()
{
int computer_side = BLACK;
char line[256], command[256], msg[356];
int from, to, i;
BOOL found;
int post = 0;
move CompMove;
ReInit(TRUE); // Init called in main
signal(SIGINT, SIG_IGN);
printf("\n");
for (;;) {
if (side == computer_side) {
if(GameStateCheck()) { // see if game is over
fflush(stdout);
ReInit(TRUE);
computer_side = NO_COLOR;
}
Think(XBOARD);
if (pv[0][0].id == 0) {
printf("(no legal moves)\n");
fflush(stdout);
computer_side = NO_COLOR;
continue;
}
CompMove = pv[0][0];
printf("move %s\n", MoveStr(CompMove));
fflush(stdout);
MakeMove(CompMove);
ply = 0;
if(GameStateCheck()) { // see if game is over
fflush(stdout);
ReInit(TRUE);
computer_side = NO_COLOR;
}
continue;
}
fgets(line, 256, stdin);
if (line[0] == '\n')
continue;
sscanf(line, "%s", command);
#ifdef DEBUG
WriteToLog(command);
#endif
if (!strcmp(command, "xboard"))
continue;
// NEW XBOARD INTERFACE CODE
if (!strcmp(command, "protover")) {
// called when xboard starts up
printf("feature myname=\"Fimbulwinter v%s\"\n", VERSION);
printf("feature ics=1\n");
fflush(stdout);
continue;
}
// HACKED "FIMBULBOARD" WINBOARD MESSAGES /////////////////////////
// All of the form (form of input) {who} {what}
if (!strcmp(command, "told")) {
// told via "tell" msg or left a msg via "message"
strcpy(msg, (line+5));
printf("tellics kibitz %s\n",msg);
printf("tellics draw\n");
fflush(stdout);
}
if (!strcmp(command, "whispered")) {
// whispered to via "whisper"
}
if (!strcmp(command, "heardkibitz")) {
// picked up a kibitz
}
if (!strcmp(command, "heardshout")) {
}
if (!strcmp(command, "heardsshout")) {
}
/*
HACKED FIMBULBOARD OUTPUTS
kibitz {arg}
whisper {arg}
shout {arg} // Don't use these two on ICC
sshout {arg}
tell {arg} {arg} // who, what
*/
///////////////////////////////////////////////////////////////////
if (!strcmp(command, "ics")) { // are we on an internet chess server?
if(line[4] == '-') {
icc = FALSE;
} else {
icc = TRUE;
}
continue;
}
if (!strcmp(command, "new")) {
ReInit(TRUE);
computer_side = BLACK;
printf("tellics say Thanks for playing me!\n");
fflush(stdout);
continue;
}
if (!strcmp(command, "quit"))
return;
if (!strcmp(command, "force")) {
computer_side = NO_COLOR;
continue;
}
if (!strcmp(command, "white")) {
side = WHITE;
xside = BLACK;
ply = 0;
hply = 0;
computer_side = BLACK;
continue;
}
if (!strcmp(command, "black")) {
side = BLACK;
xside = WHITE;
ply = 0;
hply = 0;
computer_side = WHITE;
continue;
}
if (!strcmp(command, "st")) {
sscanf(line, "st %d", &max_time);
max_time *= 1000;
max_depth = 10000;
continue;
}
if (!strcmp(command, "sd")) {
sscanf(line, "sd %d", &max_depth);
max_time = 1000000;
continue;
}
if (!strcmp(command, "time")) {
sscanf(line, "time %d", &max_time);
max_time *= 10;
// max_time /= 30;
// Very crude time management code
max_depth = 6;
// if(hply < 14) max_depth = 6;
// if(max_time < 180000) max_depth = 6;
if(max_time < 60000) max_depth = 5;
if(max_time < 10000) max_depth = 4;
if(max_time < 3000) max_depth = 3;
continue;
}
if (!strcmp(command, "otim")) {
continue;
}
if (!strcmp(command, "go")) {
computer_side = side;
continue;
}
if (!strcmp(command, "hint")) {
Think(CONSOLE);
if (pv[0][0].id == 0)
continue;
printf("Hint: %s\n", MoveStr(pv[0][0]));
fflush(stdout);
continue;
}
if (!strcmp(command, "undo")) {
if (!hply)
continue;
UnmakeMove();
ply = 0;
continue;
}
if (!strcmp(command, "remove")) {
if (hply < 2)
continue;
UnmakeMove();
UnmakeMove();
ply = 0;
continue;
}
if (!strcmp(command, "post")) {
post = 2;
continue;
}
if (!strcmp(command, "nopost")) {
post = 0;
continue;
}
from = (line[0] - 'a')+(8*(line[1]-'1'));
to = (line[2] - 'a')+(8*(line[3]-'1'));
ply = 0;
found = FALSE;
GenerateMoves();
for(i = 0; i < ms_end[0]; i++) {
if(movestack[i].m.info.from == from && movestack[i].m.info.to == to) {
found = TRUE;
// read promotion choice
if(movestack[i].m.info.bits & SM_PROMOTE) {
switch(line[4]) {
case 'n':
break;
case 'b':
i+=1;
break;
case 'r':
i+=2;
break;
default:
i+=3;
break;
}
}
break;
}
}
if (!found || !MakeMove(movestack[i].m)) {
printf("Error (unknown command): %s\n", command);
fflush(stdout);
}
else {
ply = 0;
if(GameStateCheck()) { // see if game is over
fflush(stdout);
ReInit(TRUE);
computer_side = NO_COLOR;
}
}
}
}
BOOL IsCoordNotationMove(char *buffer)
{
// Returns true if this move looks like it's in CoordNotation
unsigned int i,a,n;
a = 0;
n = 0;
for(i = 0; i < strlen(buffer); i++) {
if(isupper(buffer[i])) return FALSE;
if(buffer[i] == 'x') return FALSE;
if(buffer[i] == '=') return FALSE;
if(isalpha(buffer[i])) a++;
if(isdigit(buffer[i])) n++;
}
if(a >= 2 && n == 2) return TRUE;
return FALSE;
}
| C | CL | 52dddc9527ecd62d2c246e679a1942a227ad55da441fa9b624f0bd9afe39f632 |
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <math.h>
#include <time.h>
// mutex and the global that it protects
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
double pi_approx = 0;
// calculates the nth term in the gregory leibniz series (outlined below)
double get_term(double n) {
double term = 4.0 / (2 * n + 1);
if ((int)floor(n) & 1) {
term = 0 - term;
}
return term;
}
/*
this struct contains the parameters that each
thread uses to do it's share of the work
*/
typedef struct{
double start;
double end;
}params;
// creates a new params struct pointer
params * params_new(double start, double end) {
params * this = malloc(sizeof(params));
this->start = start;
this->end = end;
return this;
}
/*
this is the function that each of the threads calls
this function calculates the terms from 'start' to 'end'
in the gregory leibniz series for caculating pi.
http://www.wikiwand.com/en/Leibniz_formula_for_%CF%80
the series is as follows:
π=4∑ (−1)^k * (1 / (2k+1))
*/
void * leibniz(void* args) {
params * p = (params*) args;
double start = p->start;
double end = p->end;
double sum = 0;
for(; start < end; start++) {
sum += get_term(start);
}
pthread_mutex_lock(&mut);
pi_approx += sum;
pthread_mutex_unlock(&mut);
pthread_exit(0);
}
/*
The program always calculates pi using the first 'iterations'
terms of the leibniz series. The calculating of the terms is spread
among n threads, where n is an int passed as a command line arg
*/
int main(int argc, char ** argv) {
// parse num_threads from args
int num_threads = atoi(argv[1]);
pthread_t threads[num_threads];
double iterations = 5000000;
// cacluate iterations per thread
double it_per_thread = iterations / (double) num_threads;
params ** args = malloc(sizeof(params*) * num_threads);
// create num_threads threads and start them working
int t, rc;
for (t=0;t<num_threads;t++) {
double start = (double) t * it_per_thread;
double end = start + it_per_thread;
args[t] = params_new(start, end);
rc = pthread_create(&threads[t],NULL,
leibniz,(void *)args[t]);
if (rc) {
exit(-1);
}
}
// wait for the threads to join
for(t=0;t<num_threads;t++) {
pthread_join( threads[t], NULL);
free(args[t]);
}
return 0;
}
| C | CL | b633f7f2387a2a9dd4f28332d915244b947aab8fea1d6028e2119e32ce282343 |
/*===---- shaintrin.h - SHA intrinsics -------------------------------------===
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===-----------------------------------------------------------------------===
*/
#ifndef __IMMINTRIN_H
#error "Never use <shaintrin.h> directly; include <immintrin.h> instead."
#endif
#ifndef __SHAINTRIN_H
#define __SHAINTRIN_H
/* Define the default attributes for the functions in this file. */
#define __DEFAULT_FN_ATTRS __attribute__((__always_inline__, __nodebug__, __target__("sha"), __min_vector_width__(128)))
/// Performs four iterations of the inner loop of the SHA-1 message digest
/// algorithm using the starting SHA-1 state (A, B, C, D) from the 128-bit
/// vector of [4 x i32] in \a V1 and the next four 32-bit elements of the
/// message from the 128-bit vector of [4 x i32] in \a V2. Note that the
/// SHA-1 state variable E must have already been added to \a V2
/// (\c _mm_sha1nexte_epu32() can perform this step). Returns the updated
/// SHA-1 state (A, B, C, D) as a 128-bit vector of [4 x i32].
///
/// The SHA-1 algorithm has an inner loop of 80 iterations, twenty each
/// with a different combining function and rounding constant. This
/// intrinsic performs four iterations using a combining function and
/// rounding constant selected by \a M[1:0].
///
/// \headerfile <immintrin.h>
///
/// \code
/// __m128i _mm_sha1rnds4_epu32(__m128i V1, __m128i V2, const int M);
/// \endcode
///
/// This intrinsic corresponds to the \c SHA1RNDS4 instruction.
///
/// \param V1
/// A 128-bit vector of [4 x i32] containing the initial SHA-1 state.
/// \param V2
/// A 128-bit vector of [4 x i32] containing the next four elements of
/// the message, plus SHA-1 state variable E.
/// \param M
/// An immediate value where bits [1:0] select among four possible
/// combining functions and rounding constants (not specified here).
/// \returns A 128-bit vector of [4 x i32] containing the updated SHA-1 state.
#define _mm_sha1rnds4_epu32(V1, V2, M) \
__builtin_ia32_sha1rnds4((__v4si)(__m128i)(V1), (__v4si)(__m128i)(V2), (M))
/// Calculates the SHA-1 state variable E from the SHA-1 state variables in
/// the 128-bit vector of [4 x i32] in \a __X, adds that to the next set of
/// four message elements in the 128-bit vector of [4 x i32] in \a __Y, and
/// returns the result.
///
/// \headerfile <immintrin.h>
///
/// This intrinsic corresponds to the \c SHA1NEXTE instruction.
///
/// \param __X
/// A 128-bit vector of [4 x i32] containing the current SHA-1 state.
/// \param __Y
/// A 128-bit vector of [4 x i32] containing the next four elements of the
/// message.
/// \returns A 128-bit vector of [4 x i32] containing the updated SHA-1
/// values.
static __inline__ __m128i __DEFAULT_FN_ATTRS
_mm_sha1nexte_epu32(__m128i __X, __m128i __Y)
{
return (__m128i)__builtin_ia32_sha1nexte((__v4si)__X, (__v4si)__Y);
}
/// Performs an intermediate calculation for deriving the next four SHA-1
/// message elements using previous message elements from the 128-bit
/// vectors of [4 x i32] in \a __X and \a __Y, and returns the result.
///
/// \headerfile <immintrin.h>
///
/// This intrinsic corresponds to the \c SHA1MSG1 instruction.
///
/// \param __X
/// A 128-bit vector of [4 x i32] containing previous message elements.
/// \param __Y
/// A 128-bit vector of [4 x i32] containing previous message elements.
/// \returns A 128-bit vector of [4 x i32] containing the derived SHA-1
/// elements.
static __inline__ __m128i __DEFAULT_FN_ATTRS
_mm_sha1msg1_epu32(__m128i __X, __m128i __Y)
{
return (__m128i)__builtin_ia32_sha1msg1((__v4si)__X, (__v4si)__Y);
}
/// Performs the final calculation for deriving the next four SHA-1 message
/// elements using previous message elements from the 128-bit vectors of
/// [4 x i32] in \a __X and \a __Y, and returns the result.
///
/// \headerfile <immintrin.h>
///
/// This intrinsic corresponds to the \c SHA1MSG2 instruction.
///
/// \param __X
/// A 128-bit vector of [4 x i32] containing an intermediate result.
/// \param __Y
/// A 128-bit vector of [4 x i32] containing previous message values.
/// \returns A 128-bit vector of [4 x i32] containing the updated SHA-1
/// values.
static __inline__ __m128i __DEFAULT_FN_ATTRS
_mm_sha1msg2_epu32(__m128i __X, __m128i __Y)
{
return (__m128i)__builtin_ia32_sha1msg2((__v4si)__X, (__v4si)__Y);
}
/// Performs two rounds of SHA-256 operation using the following inputs: a
/// starting SHA-256 state (C, D, G, H) from the 128-bit vector of
/// [4 x i32] in \a __X; a starting SHA-256 state (A, B, E, F) from the
/// 128-bit vector of [4 x i32] in \a __Y; and a pre-computed sum of the
/// next two message elements (unsigned 32-bit integers) and corresponding
/// rounding constants from the 128-bit vector of [4 x i32] in \a __Z.
/// Returns the updated SHA-256 state (A, B, E, F) as a 128-bit vector of
/// [4 x i32].
///
/// The SHA-256 algorithm has a core loop of 64 iterations. This intrinsic
/// performs two of those iterations.
///
/// \headerfile <immintrin.h>
///
/// This intrinsic corresponds to the \c SHA256RNDS2 instruction.
///
/// \param __X
/// A 128-bit vector of [4 x i32] containing part of the initial SHA-256
/// state.
/// \param __Y
/// A 128-bit vector of [4 x i32] containing part of the initial SHA-256
/// state.
/// \param __Z
/// A 128-bit vector of [4 x i32] containing additional input to the
/// SHA-256 operation.
/// \returns A 128-bit vector of [4 x i32] containing the updated SHA-1 state.
static __inline__ __m128i __DEFAULT_FN_ATTRS
_mm_sha256rnds2_epu32(__m128i __X, __m128i __Y, __m128i __Z)
{
return (__m128i)__builtin_ia32_sha256rnds2((__v4si)__X, (__v4si)__Y, (__v4si)__Z);
}
/// Performs an intermediate calculation for deriving the next four SHA-256
/// message elements using previous message elements from the 128-bit
/// vectors of [4 x i32] in \a __X and \a __Y, and returns the result.
///
/// \headerfile <immintrin.h>
///
/// This intrinsic corresponds to the \c SHA256MSG1 instruction.
///
/// \param __X
/// A 128-bit vector of [4 x i32] containing previous message elements.
/// \param __Y
/// A 128-bit vector of [4 x i32] containing previous message elements.
/// \returns A 128-bit vector of [4 x i32] containing the updated SHA-256
/// values.
static __inline__ __m128i __DEFAULT_FN_ATTRS
_mm_sha256msg1_epu32(__m128i __X, __m128i __Y)
{
return (__m128i)__builtin_ia32_sha256msg1((__v4si)__X, (__v4si)__Y);
}
/// Performs the final calculation for deriving the next four SHA-256 message
/// elements using previous message elements from the 128-bit vectors of
/// [4 x i32] in \a __X and \a __Y, and returns the result.
///
/// \headerfile <immintrin.h>
///
/// This intrinsic corresponds to the \c SHA256MSG2 instruction.
///
/// \param __X
/// A 128-bit vector of [4 x i32] containing an intermediate result.
/// \param __Y
/// A 128-bit vector of [4 x i32] containing previous message values.
/// \returns A 128-bit vector of [4 x i32] containing the updated SHA-256
/// values.
static __inline__ __m128i __DEFAULT_FN_ATTRS
_mm_sha256msg2_epu32(__m128i __X, __m128i __Y)
{
return (__m128i)__builtin_ia32_sha256msg2((__v4si)__X, (__v4si)__Y);
}
#undef __DEFAULT_FN_ATTRS
#endif /* __SHAINTRIN_H */
| C | CL | 29dc687117c543bc40f843702b60c3e71d581a567235f645a542740d4cc182fc |
#ifdef HAVE_CONFIG_H
#include "../../../ext_config.h"
#endif
#include <php.h>
#include "../../../php_ext.h"
#include "../../../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/memory.h"
#include "kernel/object.h"
#include "kernel/fcall.h"
#include "kernel/operators.h"
/**
* Phalcon\Logger\Adapter\Blackhole
*
* Any record it can handle will be thrown away.
*/
ZEPHIR_INIT_CLASS(Phalcon_Logger_Adapter_Blackhole) {
ZEPHIR_REGISTER_CLASS_EX(Phalcon\\Logger\\Adapter, Blackhole, phalcon, logger_adapter_blackhole, phalcon_logger_adapter_ce, phalcon_logger_adapter_blackhole_method_entry, 0);
return SUCCESS;
}
/**
* Returns the internal formatter
*/
PHP_METHOD(Phalcon_Logger_Adapter_Blackhole, getFormatter) {
zval *_0, *_1$$3;
zend_long ZEPHIR_LAST_CALL_STATUS;
ZEPHIR_MM_GROW();
ZEPHIR_OBS_VAR(_0);
zephir_read_property_this(&_0, this_ptr, SL("_formatter"), PH_NOISY_CC);
if (Z_TYPE_P(_0) != IS_OBJECT) {
ZEPHIR_INIT_VAR(_1$$3);
object_init_ex(_1$$3, phalcon_logger_formatter_line_ce);
ZEPHIR_CALL_METHOD(NULL, _1$$3, "__construct", NULL, 312);
zephir_check_call_status();
zephir_update_property_this(getThis(), SL("_formatter"), _1$$3 TSRMLS_CC);
}
RETURN_MM_MEMBER(getThis(), "_formatter");
}
/**
* Writes the log to the blackhole
*/
PHP_METHOD(Phalcon_Logger_Adapter_Blackhole, logInternal) {
zval *context = NULL;
zend_long type, time;
zval *message_param = NULL, *type_param = NULL, *time_param = NULL, *context_param = NULL;
zval *message = NULL;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 4, 0, &message_param, &type_param, &time_param, &context_param);
zephir_get_strval(message, message_param);
type = zephir_get_intval(type_param);
time = zephir_get_intval(time_param);
zephir_get_arrval(context, context_param);
}
/**
* Closes the logger
*/
PHP_METHOD(Phalcon_Logger_Adapter_Blackhole, close) {
}
| C | CL | b6fbe633bd8cd9633f4c1cd3337c1f0ab0ae7fcf93197cffd71d8712f6efc1b7 |
#include <assert.h>
#include "tsvector.h"
// Not threadsafe
void TSVectorNew(ts_vector *v, int elemSize, VectorFreeFunction freefn, int initialAllocation) {
assert(v != NULL);
// Create mutex
pthread_mutexattr_t reentrantAttr;
pthread_mutexattr_init(&reentrantAttr);
pthread_mutexattr_settype(&reentrantAttr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&v->lock, &reentrantAttr);
// Create vector
VectorNew(&v->v, elemSize, freefn, initialAllocation);
}
// Not threadsafe
void TSVectorDispose(ts_vector *v) {
assert(v != NULL);
// mutex
assert(pthread_mutex_trylock(&v->lock) == 0);
pthread_mutex_unlock(&v->lock);
pthread_mutex_destroy(&v->lock);
// vector
VectorDispose(&v->v);
}
int TSVectorLength(ts_vector *v) {
assert(v != NULL);
int ret;
pthread_mutex_lock(&v->lock);
ret = VectorLength(&v->v);
pthread_mutex_unlock(&v->lock);
return ret;
}
void *TSVectorNth(ts_vector *v, int position) {
assert(v != NULL);
void* ret;
pthread_mutex_lock(&v->lock);
ret = VectorNth(&v->v, position);
pthread_mutex_unlock(&v->lock);
return ret;
}
void TSVectorInsert(ts_vector *v, const void *elemAddr, int position) {
assert(v != NULL);
pthread_mutex_lock(&v->lock);
VectorInsert(&v->v, elemAddr, position);
pthread_mutex_unlock(&v->lock);
}
void TSVectorAppend(ts_vector *v, const void *elemAddr) {
assert(v != NULL);
pthread_mutex_lock(&v->lock);
VectorAppend(&v->v, elemAddr);
pthread_mutex_unlock(&v->lock);
}
void TSVectorReplace(ts_vector *v, const void *elemAddr, int position) {
assert(v != NULL);
pthread_mutex_lock(&v->lock);
VectorReplace(&v->v, elemAddr, position);
pthread_mutex_unlock(&v->lock);
}
void TSVectorDelete(ts_vector *v, int position) {
assert(v != NULL);
pthread_mutex_lock(&v->lock);
VectorDelete(&v->v, position);
pthread_mutex_unlock(&v->lock);
}
int TSVectorSearch(ts_vector *v, const void *key, VectorCompareFunction searchfn, int startIndex, bool isSorted) {
assert(v != NULL);
int ret;
pthread_mutex_lock(&v->lock);
ret = VectorSearch(&v->v, key, searchfn, startIndex, isSorted);
pthread_mutex_unlock(&v->lock);
return ret;
}
void TSVectorSort(ts_vector *v, VectorCompareFunction comparefn) {
assert(v != NULL);
pthread_mutex_lock(&v->lock);
VectorSort(&v->v, comparefn);
pthread_mutex_unlock(&v->lock);
}
void TSVectorMap(ts_vector *v, VectorMapFunction mapfn, void *auxData) {
}
| C | CL | c4e8ba23210993e24a9e7855293c1fb2ddb48fa3e687181e6f9d0426be3439de |
#ifndef _wem_suboff_h_
#define _wem_suboff_h_
void wem_suboff(float **uz,
float **mpp,
float **wav,
int nt, float ot, float dt,
int nmx,float omx, float dmx,
int nhx,float ohx, float dhx,
float sx,
int nz, float oz, float dz, float gz, float sz,
float **velp, int nref,
float fmin, float fmax,
int padt, int padx,
bool adj, bool pspi, bool verbose,
float kz_eps);
void extrap1f(float **mpp,
complex **uz_g_wx,
complex **u_s_wx,
float max_source, int iw, int nw,int ifmax,int ntfft,float dw,float dkx,int nkx,
int nz, float oz, float dz, float gz, float sz,
int nmx,float omx, float dmx,
int nhx,float ohx, float dhx,
int nthread,
float **vp,float *po_p,float **pd_p,
float **vpref, int **ipref1, int **ipref2, int nref,
fftwf_plan p1,fftwf_plan p2,
bool adj, bool pspi, bool verbose,
float kz_eps);
void ssop(complex *d_x,
float w,float dkx,int nkx,int nmx,float omx,float dmx,float dz,int iz,
float **v,float *po,float **pd,
fftwf_plan p1,fftwf_plan p2,
fftwf_complex *a, fftwf_complex *b,
bool adj,
bool src,
bool verbose,
float kz_eps);
void pspiop(complex *d_x,
float w,float dkx,int nkx,
int nmx,float omx,float dmx,
float dz,int iz,
float **vel,float *po,float **pd,
float **vref, int **iref1, int **iref2, int nref,
fftwf_plan p1,fftwf_plan p2,
fftwf_complex *a, fftwf_complex *b,
bool adj,
bool src,
bool verbose,
float kz_eps);
float linear_interp(float x1,float x2,float x);
void f_op(complex *m,float *d,int nw,int nt,bool adj);
void progress_msg(float progress);
float signf(float a);
float signfnonzero(float a);
int compare (const void * a, const void * b);
int omp_thread_count();
void boundary_condition(complex *d_x,int nmx,int lmx);
#endif
| C | CL | 563d56ac7469560cc5a15ba1fd02bca6f0c9fd5ab8919167f89a1fa2970c852d |
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
/*****************************************************************************
* Copyright Statement:
* --------------------
* This software is protected by Copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of MediaTek Inc. (C) 2008
*
* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
* SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
* LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
* LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
* RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
* THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/
#ifdef BUILD_LK
#define LCM_PRINT printf
#else
#include <linux/string.h>
#if defined(BUILD_UBOOT)
#include <asm/arch/mt_gpio.h>
#define LCM_PRINT printf
#ifndef KERN_INFO
#define KERN_INFO
#endif
#else
#include <linux/kernel.h>
#include <mach/mt_gpio.h>
#define LCM_PRINT printk
#endif
#endif
#if 0
#define LCM_DBG(fmt, arg...) \
LCM_PRINT("[NT35516-IPS] %s (line:%d) :" fmt "\r\n", __func__, __LINE__, ## arg)
#else
#define LCM_DBG(fmt, arg...) do {} while (0)
#endif
#include "lcm_drv.h"
// ---------------------------------------------------------------------------
// Local Constants
// ---------------------------------------------------------------------------
#define FRAME_WIDTH (540)
#define FRAME_HEIGHT (960)
#define LCM_DSI_CMD_MODE
// ---------------------------------------------------------------------------
// Local Variables
// ---------------------------------------------------------------------------
static LCM_UTIL_FUNCS lcm_util = {0};
#define SET_RESET_PIN(v) (lcm_util.set_reset_pin((v)))
#define UDELAY(n) (lcm_util.udelay(n))
#define MDELAY(n) (lcm_util.mdelay(n))
// ---------------------------------------------------------------------------
// Local Functions
// ---------------------------------------------------------------------------
#define dsi_set_cmdq_V2(cmd, count, ppara, force_update) lcm_util.dsi_set_cmdq_V2(cmd, count, ppara, force_update)
#define dsi_set_cmdq(pdata, queue_size, force_update) lcm_util.dsi_set_cmdq(pdata, queue_size, force_update)
#define wrtie_cmd(cmd) lcm_util.dsi_write_cmd(cmd)
#define write_regs(addr, pdata, byte_nums) lcm_util.dsi_write_regs(addr, pdata, byte_nums)
//#define read_reg(cmd) lcm_util.DSI_dcs_read_lcm_reg(cmd)
#define read_reg_v2(cmd, buffer, buffer_size) lcm_util.dsi_dcs_read_lcm_reg_v2(cmd, buffer, buffer_size)
#define TCL_GAMMA_24
//GAMMA 24
static unsigned char lcm_initialization_setting[LCM_INIT_TABLE_SIZE_MAX] = {
/* cmd, count, params*/
0xFF, 5, 0xAA,0x55,0x25,0x01,0x00,
0xF2, 35, 0x00,0x00,0x4A,0x0A,0xA8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x01,0x51,0x00,0x01,0x00,0x01,
0xF3, 7, 0x02,0x03,0x07,0x45,0x88,0xd1,0x0D,
//#LV2 Page 0 enable
0xF0, 5, 0x55,0xAA,0x52,0x08,0x00,
0xB8, 4, 0x01,0x02,0x02,0x02,//CHG
//#Display control
0xB1, 3, 0xCC, 0x00, 0x00,
//#Timing control 4H w/ 4-delay
0xC9, 6, 0x63,0x06,0x0D,0x1A,0x17,0x00,
// Frame rate
0xBD, 5, 0x01,0x41,0x10,0x38,0x01,/*default 63Hz*/
//0xBD, 5, 0x01,0x41,0x10,0x38,0x01,/*default 63Hz*/
//0xBD, 5, 0x01,0x71,0x10,0x38,0x01,/*default 55Hz*/
//0xBD, 5, 0x01,0x96,0x10,0x38,0x01,/*default 50Hz*/
0xBC, 3, 0x00, 0x00, 0x00, //colume invert
//LV2 Page 1 enable
0xF0, 5, 0x55, 0xAA, 0x52,0x08,0x01,
//AVDD Set AVDD
0xB0, 3, 0x05, 0x05, 0x05,
//#AVEE
0xB1, 3, 0x05, 0x05, 0x05,
//#VCL
0xB2, 3, 0x01, 0x01, 0x01,
//#VGH
0xB3, 3, 0x0e, 0x0e, 0x0e,
//#VGLX
0xB4, 3, 0x0a, 0x0a, 0x0a,
//BT1 Power Control for AVDD
0xB6, 3, 0x44, 0x44, 0x44, //CHG @huangns 20120718 change avdd boosting times old {0xB6, 3, {0x44, 0x44, 0x44}},
0xB7, 3, 0x34, 0x34, 0x34,
0xB8, 3, 0x20, 0x20, 0x20,
0xB9, 3, 0x24, 0x24, 0x24,
0xBA, 3, 0x14, 0x14, 0x14,
//Setting VGMP and VGSP Voltage
0xBC, 3, 0x00, 0xc8, 0x00,
//Setting VGMN and VGSN Voltage
0xBD, 3, 0x00, 0xc8, 0x00,
//Setting VCOM Offset Voltage
0xBE, 1, 0x64,
//General Purpose Output Pins Control
0xC0, 2, 0x04, 0x00,
0xca, 1, 0x00,
0xD0, 4, 0x0a,0x10,0x0d,0x0f,
//#Gamma Setting
//R+
0xD1, 16, 0x00,0xa0,0x00,0xde,0x01,0x37,0x01,0x55,0x01,0x68,0x01,0x7f,0x01,0xa5,0x01,0xb1,
0xD2, 16, 0x01,0xda,0x01,0xff,0x02,0x27,0x02,0x58,0x02,0x85,0x02,0x87,0x02,0xb0,0x02,0xe7,
0xD3, 16, 0x03,0x04,0x03,0x22,0x03,0x3e,0x03,0x50,0x03,0x77,0x03,0x90,0x03,0xa0,0x03,0xdf,
0xD4, 4, 0x03,0xfd,0x03,0xff,
//G+
0xD5, 16, 0x00,0xa0,0x00,0xde,0x01,0x37,0x01,0x55,0x01,0x68,0x01,0x7f,0x01,0xa5,0x01,0xb1,
0xD6, 16, 0x01,0xda,0x01,0xff,0x02,0x27,0x02,0x58,0x02,0x85,0x02,0x87,0x02,0xb0,0x02,0xe7,
0xD7, 16, 0x03,0x04,0x03,0x22,0x03,0x3e,0x03,0x50,0x03,0x77,0x03,0x90,0x03,0xa0,0x03,0xdf,
0xD8, 4, 0x03,0xfd,0x03,0xff,
//B+
0xD9, 16, 0x00,0xa0,0x00,0xde,0x01,0x37,0x01,0x55,0x01,0x68,0x01,0x7f,0x01,0xa5,0x01,0xb1,
0xDd, 16, 0x01,0xda,0x01,0xff,0x02,0x27,0x02,0x58,0x02,0x85,0x02,0x87,0x02,0xb0,0x02,0xe7,
0xDe, 16, 0x03,0x04,0x03,0x22,0x03,0x3e,0x03,0x50,0x03,0x77,0x03,0x90,0x03,0xa0,0x03,0xdf,
0xDf, 4, 0x03,0xfd,0x03,0xff,
//R-
0xe0, 16, 0x00,0xa0,0x00,0xde,0x01,0x37,0x01,0x55,0x01,0x68,0x01,0x7f,0x01,0xa5,0x01,0xb1,
0xe1, 16, 0x01,0xda,0x01,0xff,0x02,0x27,0x02,0x58,0x02,0x85,0x02,0x87,0x02,0xb0,0x02,0xe7,
0xe2, 16, 0x03,0x04,0x03,0x22,0x03,0x3e,0x03,0x50,0x03,0x77,0x03,0x90,0x03,0xa0,0x03,0xdf,
0xe3, 4, 0x03,0xfd,0x03,0xff,
//G-
0xe4, 16, 0x00,0xa0,0x00,0xde,0x01,0x37,0x01,0x55,0x01,0x68,0x01,0x7f,0x01,0xa5,0x01,0xb1,
0xe5, 16, 0x01,0xda,0x01,0xff,0x02,0x27,0x02,0x58,0x02,0x85,0x02,0x87,0x02,0xb0,0x02,0xe7,
0xe6, 16, 0x03,0x04,0x03,0x22,0x03,0x3e,0x03,0x50,0x03,0x77,0x03,0x90,0x03,0xa0,0x03,0xdf,
0xe7, 4, 0x03,0xfd,0x03,0xff,
//B-
0xe8, 16, 0x00,0xa0,0x00,0xde,0x01,0x37,0x01,0x55,0x01,0x68,0x01,0x7f,0x01,0xa5,0x01,0xb1,
0xe9, 16, 0x01,0xda,0x01,0xff,0x02,0x27,0x02,0x58,0x02,0x85,0x02,0x87,0x02,0xb0,0x02,0xe7,
0xea, 16, 0x03,0x04,0x03,0x22,0x03,0x3e,0x03,0x50,0x03,0x77,0x03,0x90,0x03,0xa0,0x03,0xdf,
0xeb, 4, 0x03,0xfd,0x03,0xff,
0x3A, 1, 0x77,
// 0x36, 1, 0x10,
0x35, 1, 0x00,/*TE ON, mode=0*/
0x44, 2, 0x01, 0xE0,/* TE start line = 960/2 */
// Note
// Strongly recommend not to set Sleep out / Display On here. That will cause messed frame to be shown as later the backlight is on.
REGFLAG_DELAY, 1,
// Setting ending by predefined flag
REGFLAG_END_OF_TABLE
};
static unsigned char lcm_sleep_out_setting[] = {
// Sleep Out
0x11, 0,
REGFLAG_DELAY, 200,
// Display ON
0x29, 0,
REGFLAG_DELAY, 50,
REGFLAG_END_OF_TABLE
};
static unsigned char lcm_sleep_mode_in_setting[] = {
// Display off sequence
0x28, 0,
REGFLAG_DELAY, 100,
// Sleep Mode On
0x10, 0,
REGFLAG_DELAY, 200,
REGFLAG_END_OF_TABLE
};
static unsigned char lcm_compare_id_setting[] = {
// Display off sequence
0xF0, 5, 0x55, 0xaa, 0x52,0x08,0x00,
REGFLAG_DELAY, 10,
REGFLAG_END_OF_TABLE
};
static int push_table(unsigned char table[])
{
unsigned int i, bExit = 0;
unsigned char *p = (unsigned char *)table;
LCM_SETTING_ITEM *pSetting_item;
while(!bExit) {
pSetting_item = (LCM_SETTING_ITEM *)p;
switch (pSetting_item->cmd) {
case REGFLAG_DELAY :
MDELAY(pSetting_item->count);
p += 2;
break;
case REGFLAG_END_OF_TABLE :
p += 2;
bExit = 1;
break;
default:
dsi_set_cmdq_V2(pSetting_item->cmd,
pSetting_item->count, pSetting_item->params, 1);
MDELAY(12);
p += pSetting_item->count + 2;
break;
}
}
return p - table; //return the size of settings array.
}
#if !defined(BUILD_UBOOT) && !defined(BUILD_LK)
static int get_initialization_settings(unsigned char table[])
{
memcpy(table, lcm_initialization_setting, sizeof(lcm_initialization_setting));
return sizeof(lcm_initialization_setting);
}
static void lcm_init(void);
static void lcm_reset(void);
static int set_initialization_settings(const unsigned char table[], const int count)
{
if ( count > LCM_INIT_TABLE_SIZE_MAX ){
return -EIO;
}
memset(lcm_initialization_setting, REGFLAG_END_OF_TABLE, sizeof(lcm_initialization_setting));
memcpy(lcm_initialization_setting, table, count);
lcm_reset();
lcm_init();
push_table(lcm_sleep_out_setting);
return count;
}
#endif
// ---------------------------------------------------------------------------
// LCM Driver Implementations
// ---------------------------------------------------------------------------
static void lcm_set_util_funcs(const LCM_UTIL_FUNCS *util)
{
memcpy(&lcm_util, util, sizeof(LCM_UTIL_FUNCS));
}
static void lcm_get_params(LCM_PARAMS *params)
{
memset(params, 0, sizeof(LCM_PARAMS));
params->type = LCM_TYPE_DSI;
params->width = FRAME_WIDTH;
params->height = FRAME_HEIGHT;
// enable tearing-free
params->dbi.te_mode = LCM_DBI_TE_MODE_VSYNC_ONLY;
params->dbi.te_edge_polarity = LCM_POLARITY_RISING;
#if defined(LCM_DSI_CMD_MODE)
params->dsi.mode = CMD_MODE;
#else
params->dsi.mode = SYNC_PULSE_VDO_MODE;
#endif
// DSI
/* Command mode setting */
params->dsi.LANE_NUM = LCM_TWO_LANE;
//The following defined the fomat for data coming from LCD engine.
params->dsi.data_format.color_order = LCM_COLOR_ORDER_RGB;
params->dsi.data_format.trans_seq = LCM_DSI_TRANS_SEQ_MSB_FIRST;
params->dsi.data_format.padding = LCM_DSI_PADDING_ON_LSB;
params->dsi.data_format.format = LCM_DSI_FORMAT_RGB888;
params->dsi.packet_size=256;
params->dsi.force_dcs_packet=1;
// Video mode setting
params->dsi.intermediat_buffer_num = 2;
params->dsi.PS=LCM_PACKED_PS_24BIT_RGB888;
params->dsi.vertical_sync_active = 3;
params->dsi.vertical_backporch = 12;
params->dsi.vertical_frontporch = 2;
params->dsi.vertical_active_line = FRAME_HEIGHT;
params->dsi.horizontal_sync_active = 10;
params->dsi.horizontal_backporch = 50;
params->dsi.horizontal_frontporch = 50;
params->dsi.horizontal_active_pixel = FRAME_WIDTH;
// Bit rate calculation
params->dsi.pll_div1=20; // fref=26MHz, fvco=fref*(div1+1) (div1=0~63, fvco=500MHZ~1GHz)
params->dsi.pll_div2=0; // div2=0~15: fout=fvo/(2*div2)
}
static void lcm_reset(void)
{
SET_RESET_PIN(0);
MDELAY(20);
SET_RESET_PIN(1);
MDELAY(128);
}
static void lcm_init(void)
{
LCM_DBG();
push_table(lcm_initialization_setting);
}
static void lcm_suspend(void)
{
LCM_DBG();
unsigned int data_array[2];
data_array[0] = 0x00280500; // Display Off
dsi_set_cmdq(&data_array, 1, 1);
MDELAY(10);
data_array[0] = 0x00100500; // Sleep In
dsi_set_cmdq(&data_array, 1, 1);
MDELAY(100);
}
static void lcm_resume(void)
{
LCM_DBG();
#if defined(BUILD_UBOOT) || defined(BUILD_LK)
lcm_reset();
lcm_init();
#endif
push_table(lcm_sleep_out_setting);
}
static void lcm_update(unsigned int x, unsigned int y,
unsigned int width, unsigned int height)
{
unsigned int x0 = x;
unsigned int y0 = y;
unsigned int x1 = x0 + width - 1;
unsigned int y1 = y0 + height - 1;
unsigned char x0_MSB = ((x0>>8)&0xFF);
unsigned char x0_LSB = (x0&0xFF);
unsigned char x1_MSB = ((x1>>8)&0xFF);
unsigned char x1_LSB = (x1&0xFF);
unsigned char y0_MSB = ((y0>>8)&0xFF);
unsigned char y0_LSB = (y0&0xFF);
unsigned char y1_MSB = ((y1>>8)&0xFF);
unsigned char y1_LSB = (y1&0xFF);
unsigned int data_array[16];
data_array[0]= 0x00053902;
data_array[1]= (x1_MSB<<24)|(x0_LSB<<16)|(x0_MSB<<8)|0x2a;
data_array[2]= (x1_LSB);
data_array[3]= 0x00053902;
data_array[4]= (y1_MSB<<24)|(y0_LSB<<16)|(y0_MSB<<8)|0x2b;
data_array[5]= (y1_LSB);
data_array[6]= 0x002c3909;
dsi_set_cmdq(&data_array, 7, 0);
}
#if defined(BUILD_UBOOT) || defined(BUILD_LK)
#include "cust_adc.h"
#define LCM_MAX_VOLTAGE 2000
#define LCM_MIN_VOLTAGE 1600
extern int IMM_GetOneChannelValue(int dwChannel, int data[4], int* rawdata);
static unsigned int lcm_adc_read_chip_id()
{
int data[4] = {0, 0, 0, 0};
int tmp = 0, rc = 0, iVoltage = 0;
rc = IMM_GetOneChannelValue(AUXADC_LCD_ID_CHANNEL, data, &tmp);
if(rc < 0) {
printf("read LCD_ID vol error--Liu\n");
return 0;
}
else {
iVoltage = (data[0]*1000) + (data[1]*10) + (data[2]);
printf("read LCD_ID success, data[0]=%d, data[1]=%d, data[2]=%d, data[3]=%d, iVoltage=%d\n",
data[0], data[1], data[2], data[3], iVoltage);
if( LCM_MIN_VOLTAGE < iVoltage &&
iVoltage < LCM_MAX_VOLTAGE)
return 1;
else
return 0;
}
return 0;
}
#endif
static unsigned int lcm_compare_id(void)
{
int array[4];
char buffer[3];
char id0=0;
char id1=0;
char id2=0;
lcm_reset();//must be ahead of this function.
#if defined(BUILD_UBOOT) || defined(BUILD_LK)
// if(lcm_adc_read_chip_id())
// return 1;
#endif
array[0] = 0x00083700;// read id return two byte,version and id
dsi_set_cmdq(array, 1, 1);
read_reg_v2(0x04,buffer, 3);
id0 = buffer[0]; //should be 0x00
id1 = buffer[1];//should be 0x80
id2 = buffer[2];//should be 0x00
#if defined(BUILD_UBOOT) || defined(BUILD_LK)
printf("%s, id0 = 0x%08x\n", __func__, id0);//should be 0x00
printf("%s, id1 = 0x%08x\n", __func__, id1);//should be 0xaa
printf("%s, id2 = 0x%08x\n", __func__, id2);//should be 0x55
#endif
return 0;
}
LCM_DRIVER nt35516_dsi_ips_lcm_drv =
{
.name = "nt35516_dsi_ips",
.set_util_funcs = lcm_set_util_funcs,
.compare_id = lcm_compare_id,
.get_params = lcm_get_params,
.init = lcm_init,
.suspend = lcm_suspend,
.resume = lcm_resume,
#if defined(LCM_DSI_CMD_MODE)
.update = lcm_update,
#endif
#if !defined(BUILD_UBOOT) && !defined(BUILD_LK)
.get_initialization_settings = get_initialization_settings,
.set_initialization_settings = set_initialization_settings,
#endif
};
| C | CL | fbd2f6fcdab38243bde5dd1c237795eb2da8b7f7362304b73a5c9585d0587285 |
#ifndef HW5_COMMON
#define HW5_COMMON
// Wait and signal operations, given to semop.
#define WAIT -1
#define SIGNAL 1
// The shared memory information.
#define SHMDATA struct shmdata
SHMDATA {
int shmid;
int semkey;
int mutex;
int o;
int h;
int b;
};
// The shared memory buffer type.
#define SHMMEM struct shmmem
SHMMEM {
int OCount;
int HCount;
int BCount;
};
// The sembuf structure.
#define SEMBUF struct sembuf
// The semun structure (copied from semctl man page)
#define SEMUN union semun
SEMUN {
int val; /* Value for SETVAL */
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* Array for GETALL, SETALL */
struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */
};
void try_semop(int semkey, SEMBUF * action);
void logmolecule(char * message);
#endif
| C | CL | 3426eddc07fc66ca9a1f07cabd7a7e5c916e8847cffd6283458e6e597cec1e13 |
#ifndef XSWAP_H_
#define XSWAP_H_
/**
\file
\brief Меняет местами два массива.
*/
/**
Меняет местами массивы из элементов типа float
\param[in] n Размер массива
\param[in] x Ссылка на первый элемент первого массива
\param[in] incx Расстояние между элементами первого массива
\param[in] y Ссылка на первый элемент второго массива
\param[in] incy Расстояние между элементами второго массива
*/
void cblas_sswap (const int n, float *x, const int incx, float *y, const int incy);
/**
Меняет местами массивы из элементов типа double
\param[in] n Размер массива
\param[in] x Ссылка на первый элемент первого массива
\param[in] incx Расстояние между элементами первого массива
\param[in] y Ссылка на первый элемент второго массива
\param[in] incy Расстояние между элементами второго массива
*/
void cblas_dswap (const int n, double *x, const int incx, double *y, const int incy);
#endif // xswap.h
| C | CL | f469a2c2f2ebbf29b8a4bd91ba7e8228d97acf03805668664643397d3fc609e5 |
#include "stdafx.h"
#include "resource.h"
LRESULT CALLBACKAbout(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
HBITMAP WINAPIcopyScreenToBitmap(LPRECT lpRect);
BOOL WINAPIsaveBitmapToFile(HBITMAP hBitmap, LPSTR lpFileName);
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
DialogBox(hInstance, (LPCTSTR)IDD_ABOUTBOX, NULL, (DLGPROC)About);
return 0;
}
LRESULT CALLBACK About(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
RECTrc;
switch (uMsg)
{
case WM_INITDIALOG:
return TRUE;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
GetWindowRect(hwnd, &rc);
saveBitmapToFile(copyScreenToBitmap(&rc), "D:\\1.bmp");
EndDialog(hwnd, LOWORD(wParam));
break;
case IDCANCEL:
EndDialog(hwnd, LOWORD(wParam));
break;
}
return TRUE;
}
return FALSE;
}
HBITMAP WINAPI copyScreenToBitmap(LPRECT lpRect)// lpRect 代表选定区域
{
HDChScrDC, hMemDC;// 屏幕和内存设备描述表
HBITMAPhBitmap, hOldBitmap;// 位图句柄
intnX, nY, nX2, nY2;// 选定区域坐标
intnWidth, nHeight;// 位图宽度和高度
intxScrn, yScrn;// 屏幕分辨率
// 确保选定区域不为空矩形
if (IsRectEmpty(lpRect))return NULL;
// 为屏幕创建设备描述表
hScrDC = CreateDC("DISPLAY", NULL, NULL, NULL);
// 为屏幕设备描述表创建兼容的内存设备描述表
hMemDC = CreateCompatibleDC(hScrDC);
// 获得选定区域坐标
nX = lpRect->left;
nY = lpRect->top;
nX2 = lpRect->right;
nY2 = lpRect->bottom;
// 获得屏幕分辨率
xScrn = GetDeviceCaps(hScrDC, HORZRES);
yScrn = GetDeviceCaps(hScrDC, VERTRES);
// 确保选定区域是可见的
if (nX < 0)nX = 0;
if (nY < 0)nY = 0;
if (nX2 > xScrn)nX2 = xScrn;
if (nY2 > yScrn)nY2 = yScrn;
nWidth = nX2 - nX;
nHeight = nY2 - nY;
// 创建一个与屏幕设备描述表兼容的位图
hBitmap = CreateCompatibleBitmap(hScrDC, nWidth, nHeight);
// 把新位图选到内存设备描述表中
hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);
// 把屏幕设备描述表拷贝到内存设备描述表中
BitBlt(hMemDC, 0, 0, nWidth, nHeight, hScrDC, nX, nY, SRCCOPY);
// 得到屏幕位图的句柄
hBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
// 清除
DeleteDC(hScrDC);
DeleteDC(hMemDC);
// 返回位图句柄
return hBitmap;
}
BOOL WINAPI saveBitmapToFile(HBITMAP hBitmap,// hBitmap 为刚才的屏幕位图句柄
LPSTR lpFileName)// lpFileName 为位图文件名
{
HDChDC;// 设备描述表
intiBits;// 当前显示分辨率下每个像素所占字节数
WORDwBitCount;// 位图中每个像素所占字节数
DWORDdwPaletteSize = 0,// 定义调色板大小
dwBmBitsSize,// 位图中像素字节大小
dwDIBSize,// 位图文件大小
dwWritten;// 写入文件字节数
BITMAPBitmap;// 位图属性结构
BITMAPFILEHEADERbmfHdr;// 位图文件头结构
BITMAPINFOHEADERbi;// 位图信息头结构
LPBITMAPINFOHEADERlpbi;// 指向位图信息头结构
HANDLEfh,// 定义文件
hDib,// 分配内存句柄
hPal;// 调色板句柄
HPALETTEhOldPal = NULL;
// 计算位图文件每个像素所占字节数
hDC = CreateDC("DISPLAY", NULL, NULL, NULL);
iBits = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
DeleteDC(hDC);
if (iBits <= 1)wBitCount = 1;
else if (iBits <= 4)wBitCount = 4;
else if (iBits <= 8)wBitCount = 8;
else if (iBits <= 24)wBitCount = 24;
else wBitCount = 24;
// 计算调色板大小
if (wBitCount <= 8)dwPaletteSize = (1 << wBitCount) * sizeof(RGBQUAD);
// 设置位图信息头结构
GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&Bitmap);
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = Bitmap.bmWidth;
bi.biHeight = Bitmap.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = wBitCount;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;
dwBmBitsSize = ((Bitmap.bmWidth * wBitCount + 31) / 32) * 4 * Bitmap.bmHeight;
// 为位图内容分配内存
hDib = GlobalAlloc(GHND, dwBmBitsSize + dwPaletteSize + sizeof(BITMAPINFOHEADER));
lpbi = (LPBITMAPINFOHEADER)GlobalLock(hDib);
*lpbi = bi;
// 处理调色板
hPal = GetStockObject(DEFAULT_PALETTE);
if (hPal)
{
hDC = GetDC(NULL);
hOldPal = SelectPalette(hDC, (HPALETTE)hPal, FALSE);
RealizePalette(hDC);
}
// 获取该调色板下新的像素值
GetDIBits(hDC, hBitmap, 0, (UINT)Bitmap.bmHeight, (LPSTR)lpbi + sizeof(BITMAPINFOHEADER)+dwPaletteSize, (BITMAPINFO*)lpbi, DIB_RGB_COLORS);
// 恢复调色板
if (hOldPal)
{
SelectPalette(hDC, hOldPal, TRUE);
RealizePalette(hDC);
ReleaseDC(NULL, hDC);
}
// 创建位图文件
fh = CreateFile(lpFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (fh == INVALID_HANDLE_VALUE)return FALSE;
// 设置位图文件头
bmfHdr.bfType = 0x4D42;// "BM"
dwDIBSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+dwPaletteSize + dwBmBitsSize;
bmfHdr.bfSize = dwDIBSize;
bmfHdr.bfReserved1 = 0;
bmfHdr.bfReserved2 = 0;
bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER)+(DWORD)sizeof(BITMAPINFOHEADER)+dwPaletteSize;
// 写入位图文件头
WriteFile(fh, (LPSTR)&bmfHdr, sizeof(BITMAPFILEHEADER), &dwWritten, NULL);
// 写入位图文件其余内容
WriteFile(fh, (LPSTR)lpbi, dwDIBSize, &dwWritten, NULL);
// 清除
GlobalUnlock(hDib);
GlobalFree(hDib);
CloseHandle(fh);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////////////////////
CPaintDC dc(this);
CDC cdcMem;
CBitmap m_bitmap;
cdcMem.CreateCompatibleDC(&dc);
m_bitmap.CreateCompatibleBitmap(&cdcMem, 100, 100);
cdcMem.SelectObject(&m_bitmap);
cdcMem.LineXY(100, 100);
在上面代码中,象访问数组一样访问cdcMem的内存块,并取得象素的数据,该如何操作?
//////////////////////////////////////////////////////
// 获取位图信息大小
BITMAPINFO bmpInfo;
ZeroMemory(&bmpInfo, sizeof(BITMAPINFO));
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
int nRet = GetDIBits(dc.m_hDC, m_bitmap, 0, 0, NULL, &bmpInfo, DIB_RGB_COLORS);
if (nRet == 0)
{
return;
}
if (bmpInfo.bmiHeader.biSizeImage <= 0)
{
bmpInfo.bmiHeader.biSizeImage = bmpInfo.bmiHeader.biWidth * abs(bmpInfo.bmiHeader.biHeight) * (bmpInfo.bmiHeader.biBitCount + 7) / 8;
}
// 开辟位图数据占用的空间
LPVOID lpvBits = malloc(bmpInfo.bmiHeader.biSizeImage);
if (lpvBits == NULL)
{
return;
}
// 获取位图数据信息
bmpInfo.bmiHeader.biCompression = BI_RGB;
nRet = GetDIBits(hDC, hBitmap, 0, bmpInfo.bmiHeader.biHeight, lpvBits, &bmpInfo, DIB_RGB_COLORS);
if (nRet == 0)
{
return;
}
// 对位图信息lpvBits的操作。。。。。
// ......
// 释放开辟的空间
free(lpvBits);
lpvBits = NULL;
| C | CL | 964eae7077e9ef1b47f43213eab64d8787176b22b2cf80f0f8f12c6fd637d309 |
#define PREFIX "ACPI: "
#define ACPI_BATTERY_VALUE_UNKNOWN 0xFFFFFFFF
#define ACPI_BATTERY_CLASS "battery"
#define ACPI_BATTERY_DEVICE_NAME "Battery"
#define ACPI_BATTERY_NOTIFY_STATUS 0x80
#define ACPI_BATTERY_NOTIFY_INFO 0x81
#define ACPI_BATTERY_NOTIFY_THRESHOLD 0x82
#define _COMPONENT ACPI_BATTERY_COMPONENT
ACPI_MODULE_NAME("battery");
MODULE_AUTHOR("Paul Diefenbaugh");
MODULE_AUTHOR("Alexey Starikovskiy <[email protected]>");
MODULE_DESCRIPTION("ACPI Battery Driver");
MODULE_LICENSE("GPL");
static unsigned int cache_time = 1000;
module_param(cache_time, uint, 0644);
MODULE_PARM_DESC(cache_time, "cache time in milliseconds");
extern struct proc_dir_entry *acpi_lock_battery_dir(void);
extern void *acpi_unlock_battery_dir(struct proc_dir_entry *acpi_battery_dir);
enum acpi_battery_files ;
static const struct acpi_device_id battery_device_ids[] = ;
MODULE_DEVICE_TABLE(acpi, battery_device_ids);
enum ;
struct acpi_battery ;
#define to_acpi_battery(x) container_of(x, struct acpi_battery, bat);
inline int acpi_battery_present(struct acpi_battery *battery)
static int acpi_battery_technology(struct acpi_battery *battery)
static int acpi_battery_get_state(struct acpi_battery *battery);
static int acpi_battery_is_charged(struct acpi_battery *battery)
static int acpi_battery_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
static enum power_supply_property charge_battery_props[] = ;
static enum power_supply_property energy_battery_props[] = ;
inline char *acpi_battery_units(struct acpi_battery *battery)
struct acpi_offsets ;
static struct acpi_offsets state_offsets[] = ;
static struct acpi_offsets info_offsets[] = ;
static struct acpi_offsets extended_info_offsets[] = ;
static int extract_package(struct acpi_battery *battery,
union acpi_object *package,
struct acpi_offsets *offsets, int num)
static int acpi_battery_get_status(struct acpi_battery *battery)
static int acpi_battery_get_info(struct acpi_battery *battery)
static int acpi_battery_get_state(struct acpi_battery *battery)
static int acpi_battery_set_alarm(struct acpi_battery *battery)
static int acpi_battery_init_alarm(struct acpi_battery *battery)
static ssize_t acpi_battery_alarm_show(struct device *dev,
struct device_attribute *attr,
char *buf)
static ssize_t acpi_battery_alarm_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
static struct device_attribute alarm_attr = ;
static int sysfs_add_battery(struct acpi_battery *battery)
static void sysfs_remove_battery(struct acpi_battery *battery)
static void acpi_battery_quirks(struct acpi_battery *battery)
static void acpi_battery_quirks2(struct acpi_battery *battery)
static int acpi_battery_update(struct acpi_battery *battery)
static void acpi_battery_refresh(struct acpi_battery *battery)
static struct proc_dir_entry *acpi_battery_dir;
static int acpi_battery_print_info(struct seq_file *seq, int result)
static int acpi_battery_print_state(struct seq_file *seq, int result)
static int acpi_battery_print_alarm(struct seq_file *seq, int result)
static ssize_t acpi_battery_write_alarm(struct file *file,
const char __user * buffer,
size_t count, loff_t * ppos)
typedef int(*print_func)(struct seq_file *seq, int result);
static print_func acpi_print_funcs[ACPI_BATTERY_NUMFILES] = ;
static int acpi_battery_read(int fid, struct seq_file *seq)
#define DECLARE_FILE_FUNCTIONS(_name) \
static int acpi_battery_read_##_name(struct seq_file *seq, void *offset) \
\
static int acpi_battery_##_name##_open_fs(struct inode *inode, struct file *file) \
DECLARE_FILE_FUNCTIONS(info);
DECLARE_FILE_FUNCTIONS(state);
DECLARE_FILE_FUNCTIONS(alarm);
#undef DECLARE_FILE_FUNCTIONS
#define FILE_DESCRIPTION_RO(_name) \
#define FILE_DESCRIPTION_RW(_name) \
static struct battery_file acpi_battery_file[] = ;
#undef FILE_DESCRIPTION_RO
#undef FILE_DESCRIPTION_RW
static int acpi_battery_add_fs(struct acpi_device *device)
static void acpi_battery_remove_fs(struct acpi_device *device)
static void acpi_battery_notify(struct acpi_device *device, u32 event)
static int battery_notify(struct notifier_block *nb,
unsigned long mode, void *_unused)
static int acpi_battery_add(struct acpi_device *device)
static int acpi_battery_remove(struct acpi_device *device, int type)
static int acpi_battery_resume(struct acpi_device *device)
static struct acpi_driver acpi_battery_driver = ;
static void __init acpi_battery_init_async(void *unused, async_cookie_t cookie)
static int __init acpi_battery_init(void)
static void __exit acpi_battery_exit(void)
module_init(acpi_battery_init);
module_exit(acpi_battery_exit);
| C | CL | 05af829d413e0ea93e6406d80417281c72abf242fda5fe979491f2ba3d133bc7 |
#ifndef _SDMMC_SDCARD_H
#define _SDMMC_SDCARD_H
#include <rtthread.h>
#include <board.h>
#include "stm32f4xx.h"
#include "stm32f4xx_hal_sd.h"
#include <rtdevice.h>
#if defined(BSP_SDIO_SDCARD)
#define SD_TIMEOUT ((uint32_t)100000000)
#define SD_DMA_MODE 1 //0:轮询模式 1:DMA模式
extern SD_HandleTypeDef SDCARD_Handler;
extern HAL_SD_CardInfoTypeDef SDCardInfo;
rt_uint8_t SD_Init(void);
//rt_uint8_t HAL_SD_GetCardInfo(HAL_SD_CardInfoTypeDef *cardinfo);
//HAL_StatusTypeDef HAL_SD_GetCardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypeDef *pCardInfo);
#endif
#endif
| C | CL | f0e71f364faf823a08b299f9a421d660e5f1f552522fe35298aa69e8d0b7b45a |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
/*
===================================================================
===============================MACROS==============================
===================================================================
*/
#define BUFFER_SIZE 1024
#define MAX_ARG_COUNT 64
#define INPUT_DELIMETERS " \t\r\n\a"
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define YELLOW "\x1b[33m"
#define BLUE "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define RESET "\x1b[0m"
/*
===================================================================
=============================INTERFACE=============================
===================================================================
*/
char *set_prompt(int argc, char **argv);
void shell_loop(char *prompt);
char *get_raw_input();
char **split_args(char *raw, int *bg);
char *get_arg(char *token);
int execute(int runInBackground, char **args);
void change_directory(char **args);
void print_current_directory();
int program_command(char **args, int bg);
void check_alloc(void *ptr);
void *remove_first_and_last_chars(char *chars);
/*
===================================================================
================================MAIN===============================
===================================================================
*/
/*
Description:
This program is a simplified unix shell implemented in C.
Designed to run in a unix environment.
Note:
The code does not correctly run processes in the background.
When a process is run in the background, the output is not
correctly presented and the process will become a 'zombie'
after it completes it's execution.
*/
int main(int argc, char **argv)
{
char *prompt = set_prompt(argc, argv);
shell_loop(prompt);
free(prompt);
return 0;
}
/*
===================================================================
============================SHELL LOGIC============================
===================================================================
*/
/*
Main loop where users enter and execute commands
*/
void shell_loop(char *prompt)
{
char *raw = NULL;
char **args = NULL;
int status = 1;
int *bg = (int *)malloc(sizeof(int));
do
{
fputs(prompt, stdout);
raw = get_raw_input();
args = split_args(raw, bg);
status = execute(*bg, args);
free(raw);
free(args);
} while (status);
free(bg);
}
/*
===================================================================
==========================FORMAT ARGUMENTS=========================
===================================================================
*/
/*
Reads unaltered user input
*/
char *get_raw_input()
{
int i;
int c;
int done;
char *buffer;
size_t bufsize = BUFFER_SIZE;
buffer = (char *)malloc(bufsize * sizeof(char));
check_alloc(buffer);
for (i = 0; c = getchar();)
{
done = c == '\n' || c == EOF;
buffer[i++] = !done ? c : '\0';
if (done)
break;
if (i >= bufsize)
{
bufsize += BUFFER_SIZE;
buffer = realloc(buffer, bufsize * sizeof(char));
check_alloc(buffer);
}
}
return buffer;
}
/*
Splits arguments entered by user apart
*/
char **split_args(char *raw, int *bg)
{
int i;
int maxArgCount = MAX_ARG_COUNT;
char **args = malloc(maxArgCount * sizeof(char *));
check_alloc(args);
char *token = strtok(raw, INPUT_DELIMETERS);
for (i = 0; token; token = strtok(NULL, INPUT_DELIMETERS))
{
if (strcmp(token, "&") == 0)
{
*bg = 1;
continue;
}
args[i++] = get_arg(token);
if (i >= maxArgCount)
{
maxArgCount += MAX_ARG_COUNT;
args = realloc(args, maxArgCount * sizeof(char *));
check_alloc(args);
}
}
args[i] = NULL;
free(token);
return args;
}
/*
Returns the argument whether it is the token or a string in qto
*/
char *get_arg(char *token)
{
if (token[0] != '"' && token[0] != '\'')
return token;
char *stringArg;
char delimeter = token[0];
asprintf(&stringArg, "%s", token);
while (token = strtok(NULL, INPUT_DELIMETERS))
{
asprintf(&stringArg, "%s %s", stringArg, token);
if (token[strlen(token) - 1] == delimeter)
break;
}
remove_first_and_last_chars(stringArg);
return stringArg;
}
/*
===================================================================
==========================EXECUTE COMMANDS=========================
===================================================================
*/
/*
Execute builtins or program commands
*/
int execute(int runInBackground, char **args)
{
int status = 1;
if (args[0] == NULL)
return status;
else if (strcmp(args[0], "exit") == 0)
exit(EXIT_SUCCESS);
else if (strcmp(args[0], "pid") == 0)
printf("pid: %d\n", getpid());
else if (strcmp(args[0], "ppid") == 0)
printf("ppid: %d\n", getppid());
else if (strcmp(args[0], "cd") == 0)
change_directory(args);
else if (strcmp(args[0], "pwd") == 0)
print_current_directory();
else if (strcmp(args[0], "jobs") == 0)
printf("Not implemented, extra credit if you do\n");
else
status = program_command(args, runInBackground);
return status;
}
/*
Execute the program command
*/
int program_command(char **args, int bg)
{
int status;
int rc = fork();
if (rc < 0)
{
perror(RED "Error\n" RESET);
exit(EXIT_FAILURE);
}
if (rc == 0)
{
execvp(args[0], args);
fprintf(stderr, "Cannot exec %s: No such file or directory\n", args[0]);
kill(getpid(), SIGTERM);
}
printf("[%d] %s\n", rc, args[0]);
int guardian = bg ? fork() : 0;
if (guardian != 0 && bg)
return 1;
waitpid(rc, &status, NULL);
int exitStatus = WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status);
printf("[%d] %s Exit %d\n", rc, args[0], exitStatus);
if (guardian == 0 && bg)
{
kill(rc, SIGTERM);
kill(getpid(), SIGTERM);
}
return 1;
}
/*
Prints current working directory
*/
void print_current_directory()
{
size_t pathSize = (size_t)pathconf(".", _PC_PATH_MAX);
char *cwd = (char *)malloc(pathSize * sizeof(char));
check_alloc(cwd);
printf("%s/\n", getcwd(cwd, pathSize));
free(cwd);
}
/*
Implementation of the cd command
*/
void change_directory(char **args)
{
char *dir = args[1] == NULL ? getenv("HOME") : args[1];
if (chdir(dir) != 0)
fprintf(stderr, "cd: %s no such file or directory\n", dir);
}
/*
===================================================================
===============================HELPERS=============================
===================================================================
*/
/*
Sets prompt to either the given prompt by the user,
or the default "308sh> "
*/
char *set_prompt(int argc, char **argv)
{
char *prompt = NULL;
if (argc >= 2 && strcmp(argv[1], "-p") == 0)
{
prompt = (char *)malloc(strlen(argv[2]) * sizeof(char));
check_alloc(prompt);
strcpy(prompt, argv[2]);
}
else
{
prompt = (char *)malloc(8 * sizeof(char));
check_alloc(prompt);
strcpy(prompt, "308sh> ");
}
return prompt;
}
/*
Removes first and last characters in string or char array.
Designed for removing quote marks from strings.
*/
void *remove_first_and_last_chars(char *chars)
{
int lastCharIndex = strlen(chars) - 2;
strncpy(chars, &chars[1], lastCharIndex);
*(chars + lastCharIndex) = '\0';
}
/*
Checks that memory allocation does not fail.
Program exits on failure.
*/
void check_alloc(void *ptr)
{
if (ptr == NULL)
{
fputs("Unable to allocate memory\n", stderr);
exit(EXIT_FAILURE);
}
} | C | CL | 68613754854e39dfc4a8cb97f1d2833dffb3507db65f286332fe55376dc1d37a |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef scalar_t__ u32 ;
struct xhci_virt_ep {int dummy; } ;
struct xhci_virt_device {int /*<<< orphan*/ out_ctx; } ;
struct xhci_transfer_event {int /*<<< orphan*/ transfer_len; int /*<<< orphan*/ buffer; int /*<<< orphan*/ flags; } ;
struct xhci_td {scalar_t__ last_trb; } ;
struct xhci_ring {scalar_t__ dequeue; int /*<<< orphan*/ stream_id; } ;
struct xhci_hcd {struct xhci_virt_device** devs; } ;
struct xhci_ep_ctx {int dummy; } ;
/* Variables and functions */
scalar_t__ COMP_STALL_ERROR ;
scalar_t__ COMP_STOPPED ;
scalar_t__ COMP_STOPPED_LENGTH_INVALID ;
scalar_t__ COMP_STOPPED_SHORT_PACKET ;
int /*<<< orphan*/ EP_HARD_RESET ;
scalar_t__ GET_COMP_CODE (int /*<<< orphan*/ ) ;
int TRB_TO_EP_ID (int /*<<< orphan*/ ) ;
unsigned int TRB_TO_SLOT_ID (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ inc_deq (struct xhci_hcd*,struct xhci_ring*) ;
int /*<<< orphan*/ le32_to_cpu (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ le64_to_cpu (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ xhci_cleanup_halted_endpoint (struct xhci_hcd*,unsigned int,int,int /*<<< orphan*/ ,struct xhci_td*,int /*<<< orphan*/ ) ;
struct xhci_ring* xhci_dma_to_transfer_ring (struct xhci_virt_ep*,int /*<<< orphan*/ ) ;
struct xhci_ep_ctx* xhci_get_ep_ctx (struct xhci_hcd*,int /*<<< orphan*/ ,int) ;
scalar_t__ xhci_requires_manual_halt_cleanup (struct xhci_hcd*,struct xhci_ep_ctx*,scalar_t__) ;
int xhci_td_cleanup (struct xhci_hcd*,struct xhci_td*,struct xhci_ring*,int*) ;
__attribute__((used)) static int finish_td(struct xhci_hcd *xhci, struct xhci_td *td,
struct xhci_transfer_event *event,
struct xhci_virt_ep *ep, int *status)
{
struct xhci_virt_device *xdev;
struct xhci_ep_ctx *ep_ctx;
struct xhci_ring *ep_ring;
unsigned int slot_id;
u32 trb_comp_code;
int ep_index;
slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags));
xdev = xhci->devs[slot_id];
ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1;
ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer));
ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index);
trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len));
if (trb_comp_code == COMP_STOPPED_LENGTH_INVALID ||
trb_comp_code == COMP_STOPPED ||
trb_comp_code == COMP_STOPPED_SHORT_PACKET) {
/* The Endpoint Stop Command completion will take care of any
* stopped TDs. A stopped TD may be restarted, so don't update
* the ring dequeue pointer or take this TD off any lists yet.
*/
return 0;
}
if (trb_comp_code == COMP_STALL_ERROR ||
xhci_requires_manual_halt_cleanup(xhci, ep_ctx,
trb_comp_code)) {
/* Issue a reset endpoint command to clear the host side
* halt, followed by a set dequeue command to move the
* dequeue pointer past the TD.
* The class driver clears the device side halt later.
*/
xhci_cleanup_halted_endpoint(xhci, slot_id, ep_index,
ep_ring->stream_id, td, EP_HARD_RESET);
} else {
/* Update ring dequeue pointer */
while (ep_ring->dequeue != td->last_trb)
inc_deq(xhci, ep_ring);
inc_deq(xhci, ep_ring);
}
return xhci_td_cleanup(xhci, td, ep_ring, status);
} | C | CL | f6a1d48ccca804b7f59370051851de337c62ed5e6d8b0d76985d432fda76c170 |
/*
* Copyright (c) 2017-2018 Thomas Roell. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal with the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimers.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimers in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Thomas Roell, nor the names of its contributors
* may be used to endorse or promote products derived from this Software
* without specific prior written permission.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* WITH THE SOFTWARE.
*/
#if !defined(_STM32L0_DMA_H)
#define _STM32L0_DMA_H
#include "armv6m.h"
#include "stm32l0xx.h"
#ifdef __cplusplus
extern "C" {
#endif
#define STM32L0_DMA_CHANNEL_NONE 0x00
#define STM32L0_DMA_CHANNEL_UNDEFINED 0xf0
#define STM32L0_DMA_CHANNEL_DMA1_CH1_INDEX 0x01
#define STM32L0_DMA_CHANNEL_DMA1_CH2_INDEX 0x02
#define STM32L0_DMA_CHANNEL_DMA1_CH3_INDEX 0x03
#define STM32L0_DMA_CHANNEL_DMA1_CH4_INDEX 0x04
#define STM32L0_DMA_CHANNEL_DMA1_CH5_INDEX 0x05
#define STM32L0_DMA_CHANNEL_DMA1_CH6_INDEX 0x06
#define STM32L0_DMA_CHANNEL_DMA1_CH7_INDEX 0x07
#if defined(STM32L052xx)
#define STM32L0_DMA_CHANNEL_DMA1_CH1_ADC 0x01
#define STM32L0_DMA_CHANNEL_DMA1_CH1_TIM2_CH3 0x41
#define STM32L0_DMA_CHANNEL_DMA1_CH2_ADC 0x02
#define STM32L0_DMA_CHANNEL_DMA1_CH2_SPI1_RX 0x12
#define STM32L0_DMA_CHANNEL_DMA1_CH2_USART1_TX 0x32
#define STM32L0_DMA_CHANNEL_DMA1_CH2_LPUART1_TX 0x52
#define STM32L0_DMA_CHANNEL_DMA1_CH2_I2C1_TX 0x62
#define STM32L0_DMA_CHANNEL_DMA1_CH2_TIM2_UP 0x82
#define STM32L0_DMA_CHANNEL_DMA1_CH2_TIM6_UP 0x92
#define STM32L0_DMA_CHANNEL_DMA1_CH2_DAC1 0x92
#define STM32L0_DMA_CHANNEL_DMA1_CH3_SPI1_TX 0x13
#define STM32L0_DMA_CHANNEL_DMA1_CH3_USART1_RX 0x33
#define STM32L0_DMA_CHANNEL_DMA1_CH3_LPUART1_RX 0x53
#define STM32L0_DMA_CHANNEL_DMA1_CH3_I2C1_RX 0x63
#define STM32L0_DMA_CHANNEL_DMA1_CH3_TIM2_CH2 0x83
#define STM32L0_DMA_CHANNEL_DMA1_CH4_SPI2_RX 0x24
#define STM32L0_DMA_CHANNEL_DMA1_CH4_USART1_TX 0x34
#define STM32L0_DMA_CHANNEL_DMA1_CH4_USART2_TX 0x44
#define STM32L0_DMA_CHANNEL_DMA1_CH4_I2C2_TX 0x74
#define STM32L0_DMA_CHANNEL_DMA1_CH4_TIM2_CH4 0x84
#define STM32L0_DMA_CHANNEL_DMA1_CH5_SPI2_TX 0x25
#define STM32L0_DMA_CHANNEL_DMA1_CH5_USART1_RX 0x35
#define STM32L0_DMA_CHANNEL_DMA1_CH5_USART2_RX 0x45
#define STM32L0_DMA_CHANNEL_DMA1_CH5_I2C2_RX 0x75
#define STM32L0_DMA_CHANNEL_DMA1_CH5_TIM2_CH1 0x85
#define STM32L0_DMA_CHANNEL_DMA1_CH6_SPI2_RX 0x26
#define STM32L0_DMA_CHANNEL_DMA1_CH6_USART2_RX 0x46
#define STM32L0_DMA_CHANNEL_DMA1_CH6_LPUART1_RX 0x56
#define STM32L0_DMA_CHANNEL_DMA1_CH6_I2C1_TX 0x66
#define STM32L0_DMA_CHANNEL_DMA1_CH7_SPI2_TX 0x27
#define STM32L0_DMA_CHANNEL_DMA1_CH7_USART2_TX 0x47
#define STM32L0_DMA_CHANNEL_DMA1_CH7_LPUART1_TX 0x57
#define STM32L0_DMA_CHANNEL_DMA1_CH7_I2C1_RX 0x67
#define STM32L0_DMA_CHANNEL_DMA1_CH7_TIM2_CH2 0x87
#define STM32L0_DMA_CHANNEL_DMA1_CH7_TIM2_CH4 0x87
#endif /* STM32L052xx */
#if defined(STM32L072xx)
#define STM32L0_DMA_CHANNEL_DMA1_CH1_ADC 0x01
#define STM32L0_DMA_CHANNEL_DMA1_CH1_TIM2_CH3 0x41
#define STM32L0_DMA_CHANNEL_DMA1_CH2_ADC 0x02
#define STM32L0_DMA_CHANNEL_DMA1_CH2_SPI1_RX 0x12
#define STM32L0_DMA_CHANNEL_DMA1_CH2_USART1_TX 0x32
#define STM32L0_DMA_CHANNEL_DMA1_CH2_LPUART1_TX 0x52
#define STM32L0_DMA_CHANNEL_DMA1_CH2_I2C1_TX 0x62
#define STM32L0_DMA_CHANNEL_DMA1_CH2_TIM2_UP 0x82
#define STM32L0_DMA_CHANNEL_DMA1_CH2_TIM6_UP 0x92
#define STM32L0_DMA_CHANNEL_DMA1_CH2_DAC1 0x92
#define STM32L0_DMA_CHANNEL_DMA1_CH2_TIM3_CH3 0xa2
#define STM32L0_DMA_CHANNEL_DMA1_CH2_USART4_RX 0xc2
#define STM32L0_DMA_CHANNEL_DMA1_CH2_USART5_RX 0xd2
#define STM32L0_DMA_CHANNEL_DMA1_CH2_I2C3_TX 0xe2
#define STM32L0_DMA_CHANNEL_DMA1_CH3_SPI1_TX 0x13
#define STM32L0_DMA_CHANNEL_DMA1_CH3_USART1_RX 0x33
#define STM32L0_DMA_CHANNEL_DMA1_CH3_LPUART1_RX 0x53
#define STM32L0_DMA_CHANNEL_DMA1_CH3_I2C1_RX 0x63
#define STM32L0_DMA_CHANNEL_DMA1_CH3_TIM2_CH2 0x83
#define STM32L0_DMA_CHANNEL_DMA1_CH3_TIM3_CH4 0xa3
#define STM32L0_DMA_CHANNEL_DMA1_CH3_TIM3_UP 0xa3
#define STM32L0_DMA_CHANNEL_DMA1_CH3_USART4_TX 0xc3
#define STM32L0_DMA_CHANNEL_DMA1_CH3_USART5_TX 0xd3
#define STM32L0_DMA_CHANNEL_DMA1_CH3_I2C3_RX 0xe3
#define STM32L0_DMA_CHANNEL_DMA1_CH4_SPI2_RX 0x24
#define STM32L0_DMA_CHANNEL_DMA1_CH4_USART1_TX 0x34
#define STM32L0_DMA_CHANNEL_DMA1_CH4_USART2_TX 0x44
#define STM32L0_DMA_CHANNEL_DMA1_CH4_I2C2_TX 0x74
#define STM32L0_DMA_CHANNEL_DMA1_CH4_TIM2_CH4 0x84
#define STM32L0_DMA_CHANNEL_DMA1_CH4_I2C3_TX 0xe4
#define STM32L0_DMA_CHANNEL_DMA1_CH4_TIM7_UP 0xf4
#define STM32L0_DMA_CHANNEL_DMA1_CH4_DAC2 0xf4
#define STM32L0_DMA_CHANNEL_DMA1_CH5_SPI2_TX 0x25
#define STM32L0_DMA_CHANNEL_DMA1_CH5_USART1_RX 0x35
#define STM32L0_DMA_CHANNEL_DMA1_CH5_USART2_RX 0x45
#define STM32L0_DMA_CHANNEL_DMA1_CH5_I2C2_RX 0x75
#define STM32L0_DMA_CHANNEL_DMA1_CH5_TIM2_CH1 0x85
#define STM32L0_DMA_CHANNEL_DMA1_CH5_TIM3_CH1 0xa5
#define STM32L0_DMA_CHANNEL_DMA1_CH5_I2C3_RX 0xe5
#define STM32L0_DMA_CHANNEL_DMA1_CH6_SPI2_RX 0x26
#define STM32L0_DMA_CHANNEL_DMA1_CH6_USART2_RX 0x46
#define STM32L0_DMA_CHANNEL_DMA1_CH6_LPUART1_RX 0x56
#define STM32L0_DMA_CHANNEL_DMA1_CH6_I2C1_TX 0x66
#define STM32L0_DMA_CHANNEL_DMA1_CH6_TIM3_TRIG 0xa6
#define STM32L0_DMA_CHANNEL_DMA1_CH6_USART4_RX 0xc6
#define STM32L0_DMA_CHANNEL_DMA1_CH6_USART5_RX 0xd6
#define STM32L0_DMA_CHANNEL_DMA1_CH7_SPI2_TX 0x27
#define STM32L0_DMA_CHANNEL_DMA1_CH7_USART2_TX 0x47
#define STM32L0_DMA_CHANNEL_DMA1_CH7_LPUART1_TX 0x57
#define STM32L0_DMA_CHANNEL_DMA1_CH7_I2C1_RX 0x67
#define STM32L0_DMA_CHANNEL_DMA1_CH7_TIM2_CH2 0x87
#define STM32L0_DMA_CHANNEL_DMA1_CH7_TIM2_CH4 0x87
#define STM32L0_DMA_CHANNEL_DMA1_CH7_USART4_TX 0xc7
#define STM32L0_DMA_CHANNEL_DMA1_CH7_USART5_TX 0xd7
#endif /* STM32L072xx */
#if defined(STM32L082xx)
#define STM32L0_DMA_CHANNEL_DMA1_CH1_ADC 0x01
#define STM32L0_DMA_CHANNEL_DMA1_CH1_TIM2_CH3 0x41
#define STM32L0_DMA_CHANNEL_DMA1_CH1_AES_IN 0xb1
#define STM32L0_DMA_CHANNEL_DMA1_CH2_ADC 0x02
#define STM32L0_DMA_CHANNEL_DMA1_CH2_SPI1_RX 0x12
#define STM32L0_DMA_CHANNEL_DMA1_CH2_USART1_TX 0x32
#define STM32L0_DMA_CHANNEL_DMA1_CH2_LPUART1_TX 0x52
#define STM32L0_DMA_CHANNEL_DMA1_CH2_I2C1_TX 0x62
#define STM32L0_DMA_CHANNEL_DMA1_CH2_TIM2_UP 0x82
#define STM32L0_DMA_CHANNEL_DMA1_CH2_TIM6_UP 0x92
#define STM32L0_DMA_CHANNEL_DMA1_CH2_DAC1 0x92
#define STM32L0_DMA_CHANNEL_DMA1_CH2_TIM3_CH3 0xa2
#define STM32L0_DMA_CHANNEL_DMA1_CH2_AES_OUT 0xb2
#define STM32L0_DMA_CHANNEL_DMA1_CH2_USART4_RX 0xc2
#define STM32L0_DMA_CHANNEL_DMA1_CH2_USART5_RX 0xd2
#define STM32L0_DMA_CHANNEL_DMA1_CH2_I2C3_TX 0xe2
#define STM32L0_DMA_CHANNEL_DMA1_CH3_SPI1_TX 0x13
#define STM32L0_DMA_CHANNEL_DMA1_CH3_USART1_RX 0x33
#define STM32L0_DMA_CHANNEL_DMA1_CH3_LPUART1_RX 0x53
#define STM32L0_DMA_CHANNEL_DMA1_CH3_I2C1_RX 0x63
#define STM32L0_DMA_CHANNEL_DMA1_CH3_TIM2_CH2 0x83
#define STM32L0_DMA_CHANNEL_DMA1_CH3_TIM3_CH4 0xa3
#define STM32L0_DMA_CHANNEL_DMA1_CH3_TIM3_UP 0xa3
#define STM32L0_DMA_CHANNEL_DMA1_CH3_AES_OUT 0xb3
#define STM32L0_DMA_CHANNEL_DMA1_CH3_USART4_TX 0xc3
#define STM32L0_DMA_CHANNEL_DMA1_CH3_USART5_TX 0xd3
#define STM32L0_DMA_CHANNEL_DMA1_CH3_I2C3_RX 0xe3
#define STM32L0_DMA_CHANNEL_DMA1_CH4_SPI2_RX 0x24
#define STM32L0_DMA_CHANNEL_DMA1_CH4_USART1_TX 0x34
#define STM32L0_DMA_CHANNEL_DMA1_CH4_USART2_TX 0x44
#define STM32L0_DMA_CHANNEL_DMA1_CH4_I2C2_TX 0x74
#define STM32L0_DMA_CHANNEL_DMA1_CH4_TIM2_CH4 0x84
#define STM32L0_DMA_CHANNEL_DMA1_CH4_I2C3_TX 0xe4
#define STM32L0_DMA_CHANNEL_DMA1_CH4_TIM7_UP 0xf4
#define STM32L0_DMA_CHANNEL_DMA1_CH4_DAC2 0xf4
#define STM32L0_DMA_CHANNEL_DMA1_CH5_SPI2_TX 0x25
#define STM32L0_DMA_CHANNEL_DMA1_CH5_USART1_RX 0x35
#define STM32L0_DMA_CHANNEL_DMA1_CH5_USART2_RX 0x45
#define STM32L0_DMA_CHANNEL_DMA1_CH5_I2C2_RX 0x75
#define STM32L0_DMA_CHANNEL_DMA1_CH5_TIM2_CH1 0x85
#define STM32L0_DMA_CHANNEL_DMA1_CH5_TIM3_CH1 0xa5
#define STM32L0_DMA_CHANNEL_DMA1_CH5_AES_IN 0xb5
#define STM32L0_DMA_CHANNEL_DMA1_CH5_I2C3_RX 0xe5
#define STM32L0_DMA_CHANNEL_DMA1_CH6_SPI2_RX 0x26
#define STM32L0_DMA_CHANNEL_DMA1_CH6_USART2_RX 0x46
#define STM32L0_DMA_CHANNEL_DMA1_CH6_LPUART1_RX 0x56
#define STM32L0_DMA_CHANNEL_DMA1_CH6_I2C1_TX 0x66
#define STM32L0_DMA_CHANNEL_DMA1_CH6_TIM3_TRIG 0xa6
#define STM32L0_DMA_CHANNEL_DMA1_CH6_USART4_RX 0xc6
#define STM32L0_DMA_CHANNEL_DMA1_CH6_USART5_RX 0xd6
#define STM32L0_DMA_CHANNEL_DMA1_CH7_SPI2_TX 0x27
#define STM32L0_DMA_CHANNEL_DMA1_CH7_USART2_TX 0x47
#define STM32L0_DMA_CHANNEL_DMA1_CH7_LPUART1_TX 0x57
#define STM32L0_DMA_CHANNEL_DMA1_CH7_I2C1_RX 0x67
#define STM32L0_DMA_CHANNEL_DMA1_CH7_TIM2_CH2 0x87
#define STM32L0_DMA_CHANNEL_DMA1_CH7_TIM2_CH4 0x87
#define STM32L0_DMA_CHANNEL_DMA1_CH7_USART4_TX 0xc7
#define STM32L0_DMA_CHANNEL_DMA1_CH7_USART5_TX 0xd7
#endif /* STM32L082xx */
#define STM32L0_DMA_OPTION_EVENT_TRANSFER_DONE 0x00000002
#define STM32L0_DMA_OPTION_EVENT_TRANSFER_HALF 0x00000004
#define STM32L0_DMA_OPTION_EVENT_TRANSFER_ERROR 0x00000008
#define STM32L0_DMA_OPTION_PERIPHERAL_TO_MEMORY 0x00000000
#define STM32L0_DMA_OPTION_MEMORY_TO_PERIPHERAL 0x00000010
#define STM32L0_DMA_OPTION_CIRCULAR 0x00000020
#define STM32L0_DMA_OPTION_PERIPHERAL_DATA_INCREMENT 0x00000040
#define STM32L0_DMA_OPTION_MEMORY_DATA_INCREMENT 0x00000080
#define STM32L0_DMA_OPTION_PERIPHERAL_DATA_SIZE_MASK 0x00000300
#define STM32L0_DMA_OPTION_PERIPHERAL_DATA_SIZE_SHIFT 8
#define STM32L0_DMA_OPTION_PERIPHERAL_DATA_SIZE_8 0x00000000
#define STM32L0_DMA_OPTION_PERIPHERAL_DATA_SIZE_16 0x00000100
#define STM32L0_DMA_OPTION_PERIPHERAL_DATA_SIZE_32 0x00000200
#define STM32L0_DMA_OPTION_MEMORY_DATA_SIZE_MASK 0x00000c00
#define STM32L0_DMA_OPTION_MEMORY_DATA_SIZE_SHIFT 10
#define STM32L0_DMA_OPTION_MEMORY_DATA_SIZE_8 0x00000000
#define STM32L0_DMA_OPTION_MEMORY_DATA_SIZE_16 0x00000400
#define STM32L0_DMA_OPTION_MEMORY_DATA_SIZE_32 0x00000800
#define STM32L0_DMA_OPTION_PRIORITY_MASK 0x00003000
#define STM32L0_DMA_OPTION_PRIORITY_SHIFT 12
#define STM32L0_DMA_OPTION_PRIORITY_LOW 0x00000000
#define STM32L0_DMA_OPTION_PRIORITY_MEDIUM 0x00001000
#define STM32L0_DMA_OPTION_PRIORITY_HIGH 0x00002000
#define STM32L0_DMA_OPTION_PRIORITY_VERY_HIGH 0x00003000
// #define STM32L0_DMA_OPTION_MEMORY_TO_MEMORY 0x00004000
#define STM32L0_DMA_EVENT_TRANSFER_DONE 0x00000002
#define STM32L0_DMA_EVENT_TRANSFER_HALF 0x00000004
#define STM32L0_DMA_EVENT_TRANSFER_ERROR 0x00000008
typedef void (*stm32l0_dma_callback_t)(void *context, uint32_t events);
extern void stm32l0_dma_configure(unsigned int priority_1, unsigned int priority_2_3, unsigned int priority_4_5_6_7);
extern unsigned int stm32l0_dma_priority(unsigned int channel);
extern unsigned int stm32l0_dma_channel(unsigned int channel);
extern bool stm32l0_dma_enable(unsigned int channel, stm32l0_dma_callback_t callback, void *context);
extern void stm32l0_dma_disable(unsigned int channel);
extern void stm32l0_dma_start(unsigned int channel, uint32_t tx_data, uint32_t rx_data, uint16_t xf_count, uint32_t option);
extern uint16_t stm32l0_dma_stop(unsigned int channel);
extern uint16_t stm32l0_dma_count(unsigned int channel);
extern bool stm32l0_dma_done(unsigned int channel);
#ifdef __cplusplus
}
#endif
#endif /* _STM32L0_DMA_H */
| C | CL | 9840f5258630ce171745b89640686a0a1ff4c496d392c0b1eca207a30db1a702 |
#include <timeout_queue.h>
#include <check.h>
/** Test Cases for TMQ Insert
*/
/** NULL struct tmq *
*/
START_TEST(test_tmq_bump_null_elem)
{
int ret, key = 1;
struct tmq *tmq = tmq_create ();
struct tmq_element *elem = tmq_element_create (&key, sizeof(key));
tmq_insert (tmq, elem);
ret = tmq_bump (NULL, elem);
fail_unless ((ret != 0), "tmq_bump (NULL, elem)");
}
END_TEST
/** NULL struct tmq_elem *
*/
START_TEST(test_tmq_bump_tmq_null)
{
struct tmq *tmq= tmq_create ();
int ret;
ret = tmq_bump (tmq, NULL);
fail_unless ((ret != 0), "tmq_bump (tmq, NULL)");
}
END_TEST
/** NULL struct tmq *, NULL struct tmq_elem *
*/
START_TEST(test_tmq_bump_null_null)
{
int ret;
ret = tmq_bump (NULL, NULL);
fail_unless ((ret != 0), "tmq_bump (NULL, NULL)");
}
END_TEST
/** Bump an element that wasn't inserted
* TODO: framework has no methodology to validate that an element
* is part of a given set, i.e. this test will fail till then.
*/
#if 0
START_TEST(test_tmq_bump_element_not_in_list)
{
int ret, key = 1;
struct tmq *tmq = tmq_create ();
struct tmq_element *elem = tmq_element_create (&key, sizeof(key));
ret = tmq_bump (tmq, elem);
fail_unless ((ret != 0), "tmq_bump (element not in list)");
}
END_TEST
#endif
/** Test Case for TMQ Bump Single Element
*/
START_TEST(test_tmq_bump_one)
{
struct tmq *tmq;
struct tmq_element *elem;
int key = 100;
tmq = tmq_create ();
elem = tmq_element_create (&key, sizeof(key));
tmq_insert (tmq, elem);
tmq_bump (tmq, elem);
fail_unless ((tmq->size == 1), "Insert one test failed");
fail_unless ((elem == tmq->head), "Insert one test failed (elem != tmq->head)");
fail_unless ((elem == tmq->tail), "Insert one test failed (elem != tmq->tail)");
}
END_TEST
/** Test Case for TMQ Insert a Bunch of Elements
*/
START_TEST(test_tmq_bump_a_bunch)
{
struct tmq *tmq = tmq_create ();
struct tmq_element *elem;
int key;
for (key = 0; key < 9000; key++)
{
elem = tmq_element_create (&key, sizeof(key));
tmq_insert (tmq, elem);
}
tmq_bump (tmq, elem);
fail_unless ((tmq->size == 9000), "Insert a bunch test failed (tmq->size != 9000)");
fail_unless ((elem == tmq->head), "Insert a bunch test failed (elem != tmq->head)");
fail_unless ((elem != tmq->tail), "Insert a bunch test failed (elem == tmq->tail)");
}
END_TEST
/** Positive Tests
*/
Suite *
positive_suite (void)
{
Suite *s = suite_create ("Timeout Queue - Positive - tmq_bump");
TCase *tc = tcase_create ("Positive");
suite_add_tcase (s, tc);
tcase_add_test (tc, test_tmq_bump_one);
tcase_add_test (tc, test_tmq_bump_a_bunch);
return s;
}
/** Negative Tests
*/
Suite *
negative_suite (void)
{
Suite *s = suite_create ("Timeout Queue - Negatvie - tmq_bump");
TCase *tc = tcase_create ("Negative");
suite_add_tcase (s, tc);
tcase_add_test (tc, test_tmq_bump_null_elem);
tcase_add_test (tc, test_tmq_bump_tmq_null);
tcase_add_test (tc, test_tmq_bump_null_null);
return s;
}
/** Build the TMQ Test Suite
*/
int
main (void)
{
int n;
Suite *s;
SRunner *sr;
s = positive_suite ();
sr = srunner_create (s);
srunner_run_all (sr, CK_NORMAL);
n = srunner_ntests_failed (sr);
srunner_free (sr);
s = negative_suite ();
sr = srunner_create (s);
srunner_run_all (sr, CK_NORMAL);
n = srunner_ntests_failed (sr);
srunner_free (sr);
return (n == 0) ? 0 : 1;
}
| C | CL | 14b9580ae119e09af7c808006817a1b695289e77e571843bbc7068b19bd320ce |
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#ifndef SSLSTAT_ENUM_H
#define SSLSTAT_ENUM_H
#if defined _NATIVE_SSL_SUPPORT_
enum SSL_STATE {
SSL_NOT_CONNECTED,
SSL_PREHANDSHAKE,
SSL_WAITING_FOR_SESSION,
SSL_SENT_CLIENT_HELLO,
SSL_NEGOTIATING,
SSL_CONNECTED,
SSL_PRE_CLOSE_CONNECTION,
SSL_CLOSE_CONNECTION,
SSL_CLOSE_CONNECTION2,
SSL_SENT_SERVER_HELLO,
SSL_RECONNECTING,
SSL_ANYSTATE,
SSL_NOSTATE,
SSL_RETRY,
// Error handling states
SSL_PREHANDSHAKE_WAITING,
SSL_SENT_CLIENT_HELLO_WAITING,
SSL_SERVER_HELLO_WAITING,
SSL_Wait_ForAction_Start,
SSL_Wait_ForUI_Start,
SSL_WAIT_CERT_2,
SSL_WAIT_PASSWORD,
SSL_Wait_ForUI_End,
SSL_WAIT_DownloadStart,
SSL_WAIT_KeyExchange,
SSL_WAIT_DownloadEnd,
SSL_Wait_ForAction_End,
};
enum SSL_ACTIONS {
SSL_IGNORE,
SSL_HANDLE_ALERT,
SSL_HANDLE_HANDSHAKE,
SSL_CHANGE_CIPHER,
SSL_HANDLE_APPLICATION,
SSL_HANDLE_APPLICATION2,
SSL_HANDLE_V2_RECORD,
SSL_START_HANDSHAKE,
SSL_HANDLE_SERVER_HELLO,
SSL_HANDLE_CERTIFICATE,
SSL_HANDLE_SERVER_KEYS,
SSL_HANDLE_CERT_REQ,
SSL_HANDLE_HELLO_DONE,
SSL_HANDLE_FINISHED,
SSL_ERROR_UNEXPECTED_MESSAGE,
SSL_HANDLE_INTERNAL_ERRROR,
SSL_HANDLE_ILLEGAL_PARAMETER,
SSL_HANDLE_CLOSE,
SSL_HANDLE_DECOMPRESSION_FAIL,
SSL_HANDLE_BAD_MAC,
SSL_HANDLE_HANDSHAKE_FAIL,
SSL_HANDLE_AS_HANDSHAKE_FAIL,
SSL_HANDLE_BAD_CERT,
SSL_HANDLE_NO_CLIENT_CERT,
SSL_ERROR_UNEXPECTED_ERROR,
SSL_HANDLE_CLIENT_KEYS,
SSL_HANDLE_CERT_VERIFY,
SSL_HANDLE_CLIENT_HELLO,
SSL_HANDLE_V2_ERROR,
SSL_HANDLE_V2_SERVER_HELLO,
SSL_HANDLE_V2_SERVER_VERIFY,
SSL_HANDLE_V2_CERT_REQ,
SSL_HANDLE_V2_FINISHED
};
struct SSL_statesdescription_record{
SSL_STATE present_state;
SSL_ContentType recordtype;
SSL_ACTIONS action;
SSL_STATE default_nextstate;
};
struct SSL_statesdescription_handshake{
SSL_STATE present_state;
SSL_HandShakeType recordtype;
SSL_ACTIONS action;
SSL_STATE default_nextstate;
};
struct SSL_statesdescription_alert{
SSL_STATE present_state;
SSL_AlertDescription alerttype;
SSL_ACTIONS action;
SSL_STATE fatal_nextstate;
};
#endif
#endif // SSLSTAT_H
| C | CL | fcba80acc2eb16206a0aeae627fb3390b893cd654293de407279993584b07621 |
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <sys/time.h>
#include <netdb.h>
#include <malloc.h>
#include <getopt.h>
#include <time.h>
#include <infiniband/verbs.h>
#include "client.h"
#include "mgmt_server.h"
#define LISTEN_BACKLOG 10
//#define LISTEN_PORT 18515
//#define SEND_BUF_LENGTH 2048
static const int RDMA_BUFFER_SIZE = 2048;
char *strdupa1 (const char *s) {
char *d = malloc (strlen (s) + 1); // Space for length plus nul
if (d == NULL) return NULL; // No memory
strcpy (d,s); // Copy the characters
return d; // Return the new string
}
//Please be aware that below structs and definitions are also used in server side network_handler.c
//#define LID_SEND_RECV_FORMAT "0000:000000:000000:00000000000000000000000000000000"
//#define MAX_NODE 32
#define SERVER_INFORMATION_BUFFER_SIZE 256
void *get_in_addr(struct sockaddr *sa) {
return sa->sa_family == AF_INET
? (void *) &(((struct sockaddr_in*)sa)->sin_addr)
: (void *) &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int handle_remote_request(int node_id, char *msg, int size)
{
printf("handle_remote_request got msg %s\n", msg);
//ibapi_send_msg(node_id, reply_msg, sizeof(reply_msg));
return 0;
enum task tsk = *((enum task *)msg);
int app_id = *((int *)(msg+sizeof(enum task)));
char filename[255];
enum _file_mode mode;
//int size;
memcpy(filename, msg+sizeof(enum task)+sizeof(int), 255);
printf("handle_remote_request node %d msg %s filename %s\n", node_id, msg, filename);
switch (tsk) {
case CREATE_FILE:
mode = *((enum _file_mode *)(msg+sizeof(enum task)+sizeof(int)+255));
create_file(node_id, app_id, filename, mode);
break;
case OPEN_FILE:
size = *((int *)(msg+sizeof(enum task)+sizeof(int)+255));
open_file(node_id, app_id, filename, size);
break;
case DELETE_FILE:
break;
case READ_FILE:
break;
case WRITE_FILE:
break;
case SYNC_FILE:
break;
default:
break;
}
return 0;
}
int network_reply(int node_id, char *content)
{
return 0;
}
int server_test_function()
{
int target;
char *testtest;
testtest=calloc(RDMA_BUFFER_SIZE, sizeof(char));
int choice;
struct client_ibv_mr *testmr;
int *mr_flag;
mr_flag = calloc(MAX_NODE,sizeof(int));
do
{
printf("Interact with ?\n");
scanf("%d", &target);
}while(target==0);
testmr = calloc(MAX_NODE,sizeof(struct client_ibv_mr));
server_get_remotemr(target,testtest,RDMA_BUFFER_SIZE,&testmr[target]);
mr_flag[target]=1;
int i;
char *input_ato;
struct atomic_struct *temp_ato;
while(1)
{
printf("1. RDMA WRITE \n2. RDMA READ \n3. SEND MESSAGE\n4. SEND-REPLY PAIR\n5. ATOMIC SEND\n6. CHANGE TARGET\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("With ?\n");
scanf("%s", testtest);
server_rdma_write(target, &testmr[target], testtest, RDMA_BUFFER_SIZE);
//client_send_request(target, M_WRITE, testtest, RDMA_BUFFER_SIZE);
//ibapi_rdma_write(target, &ctx->peer_mr[target], testtest, RDMA_BUFFER_SIZE);
break;
case 2:
server_rdma_read(target, &testmr[target], testtest, RDMA_BUFFER_SIZE);
//ibapi_rdma_read(target, &ctx->peer_mr[target], testtest, RDMA_BUFFER_SIZE);
printf("%d: %s\n", target, testtest);
break;
case 3:
printf("with ?\n");
scanf("%s", testtest);
ibapi_send_message(target, testtest, RDMA_BUFFER_SIZE);
break;
case 4:
printf("with ?\n");
scanf("%s", testtest);
char *abc;
abc = calloc(4096, sizeof(char));
ibapi_send_reply(target, testtest, strlen(testtest), abc);
printf("%s\n", abc);
break;
case 5:
temp_ato = malloc(sizeof(struct atomic_struct)*16);
char *reply = malloc(4096);
int ret_size;
for(i=0;i<16;i++)
{
input_ato = malloc(32);
scanf("%s", input_ato);
temp_ato[i].vaddr = input_ato;
temp_ato[i].len = strlen(input_ato);
if(!strcmp(input_ato, "exit"))
break;
}
i=i+1;
server_atomic_send_reply(target, temp_ato, i, reply, &ret_size);
break;
case 6:
printf("change to ?\n");
scanf("%d", &target);
{
if(mr_flag[target]==1)
break;
server_get_remotemr(target,testtest,RDMA_BUFFER_SIZE,&testmr[target]);
mr_flag[target]=1;
}
break;
/*case 4:
printf("send to ?\n");
scanf("%d", &target);
printf("with size ?\n");
scanf("%d", &size);
//strcpy(ctx->send_msg[target]->data.newnode_msg, testtest);
//client_send_message(target, MSG_CLIENT_SEND);
testmr = malloc(sizeof(struct ibv_mr));
ibapi_get_remotemr(target,testtest,size,testmr);
printf("%lu.%lu\n", (long unsigned int)testmr->addr, (long unsigned int)testmr->lkey);
printf("With ?\n");
scanf("%s", testtest);
ibapi_rdma_write(target, testmr, testtest, size);
strcpy(testtest, "!!");
ibapi_rdma_read(target, testmr, testtest, size);
printf("%d: %s\n", target, testtest);
break;*/
default:
printf("Error input\n");
}
memset(testtest, 0, RDMA_BUFFER_SIZE);
}
}
// =======================================================
// Old form: int network_init(int num_node, const char *server_list[])
// =======================================================
int network_init(int ib_port)
{
ibapi_init(ib_port);
//server_test_function();
while(1);
//pthread_t thread_test;
//pthread_create(&thread_test, NULL, (void *)server_test_function, NULL);
//printf("Since this code is using to test cluster building, the following RDMA would not be processed\n");
//pthread_join(thread_test, NULL);
/*
for (i = 0; i < num_node; i++) {
ibapi_establish_connection(i, strdupa1(server_list[i+1]));
}
for (i = 0; i < num_node; i++) {
if (ibapi_exchange_mr(i, M_WRITE) != 0)
break;
}
ibapi_accept_request();
*/
return 0;
}
| C | CL | d8dd62fd01e10c58902d17ffc868f21214b14c196bc90c452072e3e73936b6ae |
/** @file
Register names for TCSS USB devices
<b>Conventions</b>:
- Prefixes:
Definitions beginning with "R_" are registers
Definitions beginning with "B_" are bits within registers
- Definitions beginning with "V_" are meaningful values of bits within the registers
Definitions beginning with "S_" are register sizes
Definitions beginning with "N_" are the bit position
- In general, SA registers are denoted by "_SA_" in register names
- Registers / bits that are different between SA generations are denoted by
"_SA_[generation_name]_" in register/bit names. e.g., "_SA_HSW_"
- Registers / bits that are different between SKUs are denoted by "_[SKU_name]"
at the end of the register/bit names
- Registers / bits of new devices introduced in a SA generation will be just named
as "_SA_" without [generation_name] inserted.
@copyright
INTEL CONFIDENTIAL
Copyright 2017 - 2019 Intel Corporation.
The source code contained or described herein and all documents related to the
source code ("Material") are owned by Intel Corporation or its suppliers or
licensors. Title to the Material remains with Intel Corporation or its suppliers
and licensors. The Material may contain trade secrets and proprietary and
confidential information of Intel Corporation and its suppliers and licensors,
and is protected by worldwide copyright and trade secret laws and treaty
provisions. No part of the Material may be used, copied, reproduced, modified,
published, uploaded, posted, transmitted, distributed, or disclosed in any way
without Intel's prior express written permission.
No license under any patent, copyright, trade secret or other intellectual
property right is granted to or conferred upon you by disclosure or delivery
of the Materials, either expressly, by implication, inducement, estoppel or
otherwise. Any license under such intellectual property rights must be
express and approved by Intel in writing.
Unless otherwise agreed by Intel in writing, you may not remove or alter
this notice or any other notice embedded in Materials by Intel or
Intel's suppliers or licensors in any way.
This file contains an 'Intel Peripheral Driver' and is uniquely identified as
"Intel Reference Module" and is licensed for Intel CPUs and chipsets under
the terms of your license agreement with Intel or your vendor. This file may
be modified by the user, subject to additional terms of the license agreement.
@par Specification Reference:
**/
#ifndef _SA_REGS_USB_H_
#define _SA_REGS_USB_H_
//
// TCSS USB3 xHCI related definitions
//
#define SA_XHCI_NORTH_BUS_NUM 0
#define SA_XHCI_NORTH_DEV_NUM 13
#define SA_XHCI_NORTH_FUNC_NUM 0
//
// TCSS USB3 xDCI related definitions
//
#define SA_XDCI_NORTH_BUS_NUM 0
#define SA_XDCI_NORTH_DEV_NUM 13
#define SA_XDCI_NORTH_FUNC_NUM 1
#define MAX_TCSS_USB3_PORTS 6
//
// xHCI definitions different from PCH
//
#define N_ICLU_SA_XHCI_OCM_MAX_REG 4
#define N_ICLN_SA_XHCI_OCM_MAX_REG 4
#define N_ICLH_SA_XHCI_OCM_MAX_REG 6
#define R_SA_XHCI_PORTSC02_USB3 0x490 ///< First USB3 PORTSC register
#define R_TCSS_USB_HOST_CR_SSPE_REG 0x80B8
#define B_TCSS_USB_HOST_CR_SSPE_REG_MASK (0xFF >> (8-MAX_TCSS_USB3_PORTS))
#define R_TCSS_USB_HOST_CR_USB3PDO 0x84FC
#define B_TCSS_USB_HOST_CR_USB3PDO_MASK (0xFF >> (8-MAX_TCSS_USB3_PORTS))
#endif
| C | CL | fa77e97616ae52ecd24184de318580b9864357b8f5dc95ea5ae82de7a0189d57 |
/*
* Author: Brian Pak <[email protected]>
*
* Copyright (c) 2014 Kaprica Security, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "libcgc.h"
#include "cgc_stdarg.h"
#include "cgc_stdlib.h"
#include "cgc_string.h"
#include "cgc_pkk.h"
#define STEG_TAG 0xD86B74D1
#define PPM_TAG 0x03259036
#define MODE_TAG 0xBB85A71C
#define TEXT_TAG 0xBFEFDDE9
#define END_TAG 0xAB660AF0
#define SECRET_TAG 0xB58333C6
#define SECRET_END_TAG 0x0507A018
#define MODE_EM 0x1337
#define MODE_EX 0x7331
#define MAX_PPM_SIZE (1 * 1024 * 1024)
#define MAX_TEXT_LEN 1000
#define GET_BIT(b, i) (((b) >> (8 - (i))) & 1)
typedef struct input {
unsigned int total_size;
unsigned int pkk_size;
pkk_t *pkk_data;
unsigned short mode;
unsigned short text_size;
char *text_data;
} input_t;
int cgc_read_n(int fd, char *buf, cgc_size_t len)
{
cgc_size_t i;
char *c = buf;
for (i = 0; i < len; ++i)
{
cgc_size_t rx;
if (cgc_receive(fd, c, 1, &rx) != 0 || rx == 0)
break;
c++;
}
return c - buf;
}
int cgc_readuntil(int fd, char *buf, cgc_size_t len, char delim)
{
cgc_size_t i;
char *c = buf;
for (i = 0; i < len; ++i)
{
cgc_size_t rx;
if (cgc_receive(fd, c, 1, &rx) != 0 || rx == 0)
break;
if (*(c++) == delim)
break;
}
*(c-1) = '\0';
return c - buf;
}
void cgc_cleanup_input(input_t *input)
{
if (input)
{
if (input->pkk_data)
cgc_free_pkk(input->pkk_data);
if (input->text_data)
cgc_free(input->text_data);
cgc_free(input);
}
}
input_t* cgc_parse_input()
{
unsigned int dword;
unsigned short word;
input_t *input = NULL;
unsigned int total_bytes = 0;
input = (input_t *) cgc_malloc(sizeof(input_t));
if (input == NULL)
goto fail;
if (cgc_read_n(STDIN, (char *)&dword, sizeof(dword)) != sizeof(dword) || dword != STEG_TAG)
goto fail;
total_bytes += sizeof(dword);
if (cgc_read_n(STDIN, (char *)&dword, sizeof(dword)) != sizeof(dword))
goto fail;
total_bytes += sizeof(dword);
input->total_size = dword;
if (cgc_read_n(STDIN, (char *)&dword, sizeof(dword)) != sizeof(dword) || dword != PPM_TAG)
goto fail;
total_bytes += sizeof(dword);
if (cgc_read_n(STDIN, (char *)&dword, sizeof(dword)) != sizeof(dword))
goto fail;
total_bytes += sizeof(dword);
input->pkk_size = dword;
if (input->pkk_size > 0 && input->pkk_size < MAX_PPM_SIZE)
{
char *pkk_data = cgc_malloc(input->pkk_size);
if (cgc_read_n(STDIN, pkk_data, input->pkk_size) != input->pkk_size)
goto fail;
input->pkk_data = cgc_parse_pkk(pkk_data, input->pkk_size);
if (input->pkk_data == NULL)
goto fail;
total_bytes += input->pkk_size;
}
if (cgc_read_n(STDIN, (char *)&dword, sizeof(dword)) != sizeof(dword) || dword != MODE_TAG)
goto fail;
total_bytes += sizeof(dword);
if (cgc_read_n(STDIN, (char *)&word, sizeof(word)) != sizeof(word))
goto fail;
total_bytes += sizeof(word);
input->mode = word;
if (cgc_read_n(STDIN, (char *)&dword, sizeof(dword)) != sizeof(dword) || dword != TEXT_TAG)
goto fail;
total_bytes += sizeof(dword);
if (cgc_read_n(STDIN, (char *)&word, sizeof(word)) != sizeof(word))
goto fail;
total_bytes += sizeof(word);
input->text_size = word;
if (input->text_size > 0)
{
if (input->text_size > MAX_TEXT_LEN)
goto fail;
input->text_data = cgc_malloc(input->text_size);
if (cgc_read_n(STDIN, (char *)input->text_data, input->text_size) != input->text_size)
goto fail;
total_bytes += input->text_size;
}
if (cgc_read_n(STDIN, (char *)&dword, sizeof(dword)) != sizeof(dword) || dword != END_TAG)
goto fail;
total_bytes += sizeof(dword);
if (total_bytes != input->total_size)
goto fail;
return input;
fail:
cgc_cleanup_input(input);
return NULL;
}
int cgc_embed_text(pkk_t *pkk, char *text, unsigned short len)
{
int size;
char *message, *cur;
char *pixel;
if (pkk && text && pkk->pixels)
{
pixel = (char *) pkk->pixels;
size = sizeof(int) * 2 + sizeof(short) + len;
if (pkk->width * pkk->height * sizeof(pixel_t) / 8 < size)
return -1;
message = cgc_malloc(size);
if (message == NULL)
return -1;
cur = message;
*(int *)cur = SECRET_TAG;
cur += sizeof(int);
*(short *)cur = len;
cur += sizeof(short);
cgc_memcpy(cur, text, len);
cur += len;
*(int *)cur = SECRET_END_TAG;
int i, j;
for (i = 0; i < size; ++i)
{
char c = message[i];
for (j = 1; j <= 8; ++j)
{
int lsb = *pixel & 1;
if (lsb != GET_BIT(c, j))
{
if (lsb)
*pixel = *pixel & ~1;
else
*pixel = *pixel | 1;
}
pixel++;
}
}
return 0;
}
return -1;
}
char cgc_recover_byte(char **pixel)
{
int j;
char c = '\0';
for (j = 0; j < 8; ++j)
{
c = c << 1;
int lsb = **pixel & 1;
c |= lsb;
(*pixel)++;
}
return c;
}
int cgc_extract_text(pkk_t *pkk, char *buf)
{
char c;
char *pixel;
if (pkk && buf && pkk->pixels)
{
int i, j, tag = 0;
short text_size;
pixel = (char *) pkk->pixels;
for (i = 0; i < 4; ++i)
{
c = cgc_recover_byte(&pixel);
tag |= ((c << 8*i) & (0xFF << 8*i));
}
if (tag != SECRET_TAG)
return -1;
for (i = 0; i < 2; ++i)
{
c = cgc_recover_byte(&pixel);
text_size |= ((c << 8*i) & (0xFF << 8*i));
}
/* Bug: Not checking text_size */
#if PATCHED
for (i = 0; i < text_size && i < MAX_TEXT_LEN; ++i)
#else
for (i = 0; i < text_size; ++i)
#endif
{
c = cgc_recover_byte(&pixel);
buf[i] = c;
}
tag = 0;
for (i = 0; i < 4; ++i)
{
c = cgc_recover_byte(&pixel);
tag |= ((c << 8*i) & (0xFF << 8*i));
}
if (tag != SECRET_END_TAG)
return -1;
return 0;
}
return -1;
}
int main(int cgc_argc, char *cgc_argv[])
{
char text[MAX_TEXT_LEN];
int out_len;
char *output;
input_t *input;
if ((input = cgc_parse_input()) == NULL)
{
cgc_printf("[ERROR] Failed to parse input.\n");
return -1;
}
switch (input->mode)
{
case MODE_EM:
if (cgc_embed_text(input->pkk_data, input->text_data, input->text_size) != 0)
cgc_printf("[ERROR] Failed to embed your message.\n");
else
{
output = cgc_output_pkk(input->pkk_data, &out_len);
if (output)
{
cgc_transmit(STDOUT, output, out_len, NULL);
cgc_free(output);
}
}
break;
case MODE_EX:
if (cgc_extract_text(input->pkk_data, text) != 0)
cgc_printf("[ERROR] Failed to extract the message.\n");
else
{
cgc_printf("Secret Text: %s\n", text);
}
break;
default:
cgc_printf("[ERROR] Invalid mode.\n");
break;
}
cgc_cleanup_input(input);
return 0;
}
| C | CL | cce6ad2c23eb806ea4a2d85b1b247f882cf88160893c3e78dbae9625e1714409 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_11__ TYPE_2__ ;
typedef struct TYPE_10__ TYPE_1__ ;
/* Type definitions */
struct TYPE_11__ {int dma_bits; int /*<<< orphan*/ bdev; int /*<<< orphan*/ devices_max; int /*<<< orphan*/ devices; int /*<<< orphan*/ parent; } ;
struct TYPE_10__ {int sc_id_vendor; int sc_flags; TYPE_2__ sc_bus; int /*<<< orphan*/ sc_vendor; int /*<<< orphan*/ * sc_intr_hdl; int /*<<< orphan*/ * sc_irq_res; int /*<<< orphan*/ * sc_io_tag; int /*<<< orphan*/ sc_io_hdl; int /*<<< orphan*/ * sc_io_res; int /*<<< orphan*/ sc_devices; } ;
typedef TYPE_1__ ehci_softc_t ;
typedef int /*<<< orphan*/ driver_intr_t ;
typedef int /*<<< orphan*/ device_t ;
typedef int /*<<< orphan*/ bus_space_tag_t ;
typedef int /*<<< orphan*/ bus_space_handle_t ;
/* Variables and functions */
int /*<<< orphan*/ EHCI_MAX_DEVICES ;
int EHCI_SCFLG_DONEINIT ;
int EHCI_SCFLG_DONTRESET ;
int EHCI_SCFLG_NORESTERM ;
int EIO ;
int ENOMEM ;
int ENXIO ;
int /*<<< orphan*/ FSL_EHCI_REG_OFF ;
int /*<<< orphan*/ FSL_EHCI_REG_SIZE ;
int INTR_MPSAFE ;
int INTR_TYPE_BIO ;
int /*<<< orphan*/ RF_ACTIVE ;
int /*<<< orphan*/ SYS_RES_IRQ ;
int /*<<< orphan*/ SYS_RES_MEMORY ;
int /*<<< orphan*/ USB_GET_DMA_TAG (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ bs_le_tag ;
void* bus_alloc_resource_any (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int*,int /*<<< orphan*/ ) ;
int bus_setup_intr (int /*<<< orphan*/ ,int /*<<< orphan*/ *,int,int /*<<< orphan*/ *,int /*<<< orphan*/ *,TYPE_1__*,int /*<<< orphan*/ **) ;
int bus_space_subregion (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ clear_port_power (TYPE_1__*) ;
int /*<<< orphan*/ device_add_child (int /*<<< orphan*/ ,char*,int) ;
TYPE_1__* device_get_softc (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ device_printf (int /*<<< orphan*/ ,char*,...) ;
int device_probe_and_attach (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ device_set_ivars (int /*<<< orphan*/ ,TYPE_2__*) ;
int ehci_init (TYPE_1__*) ;
scalar_t__ ehci_interrupt ;
int /*<<< orphan*/ ehci_iterate_hw_softc ;
int ehci_reset (TYPE_1__*) ;
int /*<<< orphan*/ enable_usb (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int fsl_ehci_detach (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ rman_get_bushandle (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ rman_get_bustag (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ set_32b_prefetch (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ set_snooping (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ set_to_host_mode (TYPE_1__*) ;
int /*<<< orphan*/ strlcpy (int /*<<< orphan*/ ,char*,int) ;
scalar_t__ usb_bus_mem_alloc_all (TYPE_2__*,int /*<<< orphan*/ ,int /*<<< orphan*/ *) ;
__attribute__((used)) static int
fsl_ehci_attach(device_t self)
{
ehci_softc_t *sc;
int rid;
int err;
bus_space_handle_t ioh;
bus_space_tag_t iot;
sc = device_get_softc(self);
rid = 0;
sc->sc_bus.parent = self;
sc->sc_bus.devices = sc->sc_devices;
sc->sc_bus.devices_max = EHCI_MAX_DEVICES;
sc->sc_bus.dma_bits = 32;
if (usb_bus_mem_alloc_all(&sc->sc_bus,
USB_GET_DMA_TAG(self), &ehci_iterate_hw_softc))
return (ENOMEM);
/* Allocate io resource for EHCI */
sc->sc_io_res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid,
RF_ACTIVE);
if (sc->sc_io_res == NULL) {
err = fsl_ehci_detach(self);
if (err) {
device_printf(self,
"Detach of the driver failed with error %d\n",
err);
}
return (ENXIO);
}
iot = rman_get_bustag(sc->sc_io_res);
/*
* Set handle to USB related registers subregion used by generic
* EHCI driver
*/
ioh = rman_get_bushandle(sc->sc_io_res);
err = bus_space_subregion(iot, ioh, FSL_EHCI_REG_OFF, FSL_EHCI_REG_SIZE,
&sc->sc_io_hdl);
if (err != 0) {
err = fsl_ehci_detach(self);
if (err) {
device_printf(self,
"Detach of the driver failed with error %d\n",
err);
}
return (ENXIO);
}
/* Set little-endian tag for use by the generic EHCI driver */
sc->sc_io_tag = &bs_le_tag;
/* Allocate irq */
sc->sc_irq_res = bus_alloc_resource_any(self, SYS_RES_IRQ, &rid,
RF_ACTIVE);
if (sc->sc_irq_res == NULL) {
err = fsl_ehci_detach(self);
if (err) {
device_printf(self,
"Detach of the driver failed with error %d\n",
err);
}
return (ENXIO);
}
/* Setup interrupt handler */
err = bus_setup_intr(self, sc->sc_irq_res, INTR_TYPE_BIO | INTR_MPSAFE,
NULL, (driver_intr_t *)ehci_interrupt, sc, &sc->sc_intr_hdl);
if (err) {
device_printf(self, "Could not setup irq, %d\n", err);
sc->sc_intr_hdl = NULL;
err = fsl_ehci_detach(self);
if (err) {
device_printf(self,
"Detach of the driver failed with error %d\n",
err);
}
return (ENXIO);
}
/* Add USB device */
sc->sc_bus.bdev = device_add_child(self, "usbus", -1);
if (!sc->sc_bus.bdev) {
device_printf(self, "Could not add USB device\n");
err = fsl_ehci_detach(self);
if (err) {
device_printf(self,
"Detach of the driver failed with error %d\n",
err);
}
return (ENOMEM);
}
device_set_ivars(sc->sc_bus.bdev, &sc->sc_bus);
sc->sc_id_vendor = 0x1234;
strlcpy(sc->sc_vendor, "Freescale", sizeof(sc->sc_vendor));
/* Enable USB */
err = ehci_reset(sc);
if (err) {
device_printf(self, "Could not reset the controller\n");
err = fsl_ehci_detach(self);
if (err) {
device_printf(self,
"Detach of the driver failed with error %d\n",
err);
}
return (ENXIO);
}
enable_usb(self, iot, ioh);
set_snooping(iot, ioh);
set_to_host_mode(sc);
set_32b_prefetch(iot, ioh);
/*
* If usb subsystem is enabled in U-Boot, port power has to be turned
* off to allow proper discovery of devices during boot up.
*/
clear_port_power(sc);
/* Set flags */
sc->sc_flags |= EHCI_SCFLG_DONTRESET | EHCI_SCFLG_NORESTERM;
err = ehci_init(sc);
if (!err) {
sc->sc_flags |= EHCI_SCFLG_DONEINIT;
err = device_probe_and_attach(sc->sc_bus.bdev);
}
if (err) {
device_printf(self, "USB init failed err=%d\n", err);
err = fsl_ehci_detach(self);
if (err) {
device_printf(self,
"Detach of the driver failed with error %d\n",
err);
}
return (EIO);
}
return (0);
} | C | CL | bed542775870fcdec82cb5e0b73e9ef6c91a0dba2e2e1b42f05ef9ce60021d50 |
/*
* airkiss_cloud.h
*
* Created on: 2016年3月31日
* Author: itmaktub
*/
#ifndef APP_USER_AIRKISS_CLOUD_H_
#define APP_USER_AIRKISS_CLOUD_H_
#if defined(GLOBAL_DEBUG)
#define AIRKISS_CLOUD_DEBUG(format, ...) log_printf("AIRKISS_CLOUD: ", format, ##__VA_ARGS__)
#else
#define AIRKISS_CLOUD_DEBUG(format, ...)
#endif
#define AIRKISS_HEAP_MAX 1024*4
//TODO
#define DEVICE_LICENCE "FIXME"
typedef enum airkiss_cloud_receive_msg_t
{
AIRKISS_CLOUD_NOTIFY_MSG,
AIRKISS_CLOUD_RESPONSE_MSG,
AIRKISS_CLOUD_EVENT_MSG
}airkiss_cloud_receive_msg_t;
typedef enum airkiss_cloud_error_msg_t
{
AIRKISS_CLOUD_ERROR_OK = 0, // 0 厂家异步处理成功
AIRKISS_CLOUD_ERROR_BUSY = 11500, // 1 150 0 系统繁忙
AIRKISS_CLOUD_ERROR_NOT_CONNECT = 11501, // 1 150 1 设备没联网
AIRKISS_CLOUD_ERROR_POWER_OFF = 11502, // 1 150 2 设备已经关机
AIRKISS_CLOUD_ERROR_UNKOWN = 11503 // 1 150 3 设备暂时无法操作,请微信平台稍后重试
}airkiss_cloud_error_msg_t;
enum
{
AIRKISS_CLOUD_FUNC_ABILITY = 0x0001, // 0x0001 微信硬件平台能力项业务FuncID
AIRKISS_CLOUD_FUNC_FIRMWARE = 0x0020 // 0x0020 微信硬件平台固件管理业务FuncID
};
uint8_t airkiss_cloud_start(void);
typedef int (* airiss_cloud_receive_notify_callback_t)(const uint8_t *dat, uint32_t len);
typedef void (* airiss_cloud_initdone_callback_t)(void);
#define airkiss_cloud_send_ablity_msg(dat) airkiss_cloud_sendmessage(AIRKISS_CLOUD_FUNC_ABILITY, dat, os_strlen(dat));
//消息回调处理注册接口
void airiss_cloud_receive_notify_callback_register(airiss_cloud_receive_notify_callback_t airiss_cloud_receive_notify_callback);
//airkiss cloud 初始化成功后的回调注册接口
void airiss_cloud_initdone_callback_register(airiss_cloud_initdone_callback_t airiss_cloud_initdone_callback);
#endif /* APP_USER_AIRKISS_CLOUD_H_ */
| C | CL | 1d5370aeeacf6125a50e79f7214a8a966b89e30221510407abdd2de62cf31efb |
/**
* @file rsi_commands.h
* @brief Header for rsi_commands.c
* @author Keith Broerman
* @version 0.1
* @date 2014-05-22
*/
#ifndef RSI_COMMANDS_H_
#define RSI_COMMANDS_H_
#include "commonTypes.h"
sInt32_t processPollRsd(uInt8_t * rsiResponseFrame);
sInt32_t processPollApm(uInt8_t * rsiResponseFrame);
sInt32_t processApmTimedUnlock(uInt8_t * rsiRequestFrame, uInt8_t * rsiResponseFrame);
#endif /* RSI_COMMANDS_H_ */
| C | CL | 44edd6e90b8264dfe0fc20cc1f3b0387cb3d947d61bc52856006743852c14bb0 |
//
// This file is AUTOMATICALLY GENERATED, and should not be edited unless you are certain
// that it will not be re-generated anytime in the future. As generated code, the
// copyright owner(s) of the generating program do NOT claim any copyright on the code
// generated.
//
// Run Length Encoded (RLE) bitmaps. Each run is encoded as either one or two bytes,
// with NO PADDING. Thus, the data for each line of the bitmap is VARIABLE LENGTH, and
// there is no way of determining where any line other than the first starts without
// walking though the data.
//
// Note that one byte encoding ONLY occurs if the total number of colors is 16 or less,
// and in that case the 'flags' member of the 'RLEBitmapInfo' will have the first bit
// (0x01) set.
//
// In that case, if the high 4 bits of the first byte are ZERO, then this is a 2 byte
// run. The first byte is the index of the color in the color palette, and the second
// byte is the length.
//
// Else, the lower 4 bits are the color index, and the upper 4 bits are the run length.
//
// If the 'flags' member first bit is zero, then ALL runs are 2 byte runs. The first
// byte is the palette index, and the second is the run length.
//
// In order to save PROGMEM for other uses, the bitmap data is placed in a section that
// occurs near the END of the used FLASH. So, this data should only be accessed using
// the 'far' versions of the progmem functions - the usual versions are limited to the
// first 64K of FLASH.
//
// Data is from file '..\Processed\Wind\wi-wind-beaufort-10.bmp'.
//
const byte wi_wind_beaufort_10_RLEBM_data[] PROGMEM_LATE =
{
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x49, 0x11, 0x00, 0x33,
0x00, 0x46, 0x81, 0x00, 0x2f,
0x00, 0x44, 0xb1, 0x00, 0x2e,
0x00, 0x44, 0xc1, 0x00, 0x2d,
0x00, 0x43, 0xd1, 0x00, 0x2d,
0x00, 0x44, 0xd1, 0x00, 0x2c,
0x00, 0x44, 0x41, 0x30, 0x61, 0x00, 0x2c,
0x00, 0x4c, 0x51, 0x00, 0x2c,
0x00, 0x4c, 0x51, 0x00, 0x2c,
0x00, 0x4c, 0x51, 0x00, 0x2c,
0x00, 0x4a, 0x71, 0x00, 0x2c,
0xe0, 0x01, 0x43, 0x00, 0x2c,
0xd0, 0x01, 0x43, 0x00, 0x2d,
0xd0, 0x01, 0x42, 0x00, 0x2e,
0xe0, 0x01, 0x40, 0x00, 0x2f,
0xf0, 0x01, 0x3d, 0x00, 0x31,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0xf0, 0x01, 0x2f, 0x00, 0x3f,
0xe0, 0x01, 0x32, 0x00, 0x3d,
0xd0, 0x01, 0x34, 0x00, 0x3c,
0xd0, 0x01, 0x35, 0x00, 0x3b,
0xe0, 0x01, 0x34, 0x80, 0xa1, 0x00, 0x10, 0x21, 0x00, 0x17,
0x00, 0x3c, 0x71, 0x60, 0xb1, 0xb0, 0xb1, 0x00, 0x13,
0x00, 0x3d, 0x61, 0x60, 0xb1, 0x90, 0xf1, 0x00, 0x11,
0x00, 0x3e, 0x51, 0x60, 0xb1, 0x80, 0x01, 0x11, 0x00, 0x10,
0x00, 0x3e, 0x51, 0x60, 0xb1, 0x70, 0x01, 0x13, 0xf0,
0x00, 0x36, 0x41, 0x30, 0x61, 0x60, 0xa1, 0x70, 0x01, 0x15, 0xe0,
0x00, 0x35, 0xe1, 0x50, 0xb1, 0x60, 0x01, 0x16, 0xe0,
0x00, 0x35, 0xd1, 0x60, 0xb1, 0x50, 0x01, 0x18, 0xd0,
0x00, 0x35, 0xd1, 0x60, 0xb1, 0x40, 0xc1, 0x30, 0xa1, 0xd0,
0x00, 0x36, 0xb1, 0x70, 0xb1, 0x40, 0xa1, 0x60, 0x91, 0xd0,
0x00, 0x37, 0x81, 0x80, 0xb1, 0x40, 0xa1, 0x80, 0x91, 0xc0,
0x00, 0x3a, 0x21, 0xb0, 0xb1, 0x40, 0xa1, 0x80, 0x91, 0xc0,
0x00, 0x47, 0xb1, 0x40, 0x91, 0x90, 0x91, 0xc0,
0x00, 0x47, 0xb1, 0x30, 0xa1, 0x90, 0x91, 0xc0,
0x00, 0x47, 0xa1, 0x40, 0x91, 0xa0, 0x91, 0xc0,
0x00, 0x46, 0xb1, 0x40, 0x91, 0xa0, 0x91, 0xc0,
0x00, 0x46, 0xb1, 0x40, 0x91, 0x90, 0xa1, 0xc0,
0x00, 0x46, 0xb1, 0x30, 0xa1, 0x90, 0xa1, 0xc0,
0x00, 0x46, 0xb1, 0x30, 0xa1, 0x90, 0x91, 0xd0,
0x00, 0x46, 0xa1, 0x40, 0x91, 0xa0, 0x91, 0xd0,
0x00, 0x45, 0xb1, 0x40, 0x91, 0xa0, 0x91, 0xd0,
0x00, 0x45, 0xb1, 0x40, 0x91, 0x90, 0xa1, 0xd0,
0x00, 0x45, 0xb1, 0x40, 0x91, 0x90, 0x91, 0xe0,
0x00, 0x45, 0xb1, 0x40, 0xa1, 0x70, 0xa1, 0xe0,
0x00, 0x45, 0xa1, 0x60, 0x91, 0x60, 0xa1, 0xf0,
0x00, 0x44, 0xb1, 0x60, 0xa1, 0x40, 0xb1, 0xf0,
0x00, 0x44, 0xb1, 0x60, 0x01, 0x18, 0x00, 0x10,
0x00, 0x44, 0xb1, 0x60, 0x01, 0x18, 0x00, 0x10,
0x00, 0x44, 0xb1, 0x70, 0x01, 0x16, 0x00, 0x11,
0x00, 0x44, 0xa1, 0x90, 0x01, 0x14, 0x00, 0x12,
0x00, 0x43, 0xb1, 0x90, 0x01, 0x13, 0x00, 0x13,
0x00, 0x43, 0xb1, 0xb0, 0x01, 0x10, 0x00, 0x14,
0x00, 0x43, 0xb1, 0xc0, 0xd1, 0x00, 0x16,
0x00, 0x43, 0xb1, 0xe0, 0x91, 0x00, 0x18,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
0x00, 0x7d,
}; // 125x125 Bitmap (15625 pixels) in 534 bytes
const uint16_t wi_wind_beaufort_10_RLEBM_palette[] PROGMEM_LATE =
{
// Palette has 2 entries
0x0000, 0xffff,
};
// Some platforms don't fully implement the pgmspace.h interface. Assume ordinary
// addresses will do.
#if not defined pgm_get_far_address
#define pgm_get_far_address(x) ((uint32_t)(&(x)))
#endif
// Returns the info needed to render the bitmap.
inline void get_wi_wind_beaufort_10_RLEBM(
RLEBitmapInfo &bmInfo)
{
bmInfo.pRLEBM_data_far = pgm_get_far_address(wi_wind_beaufort_10_RLEBM_data);
bmInfo.pRLEBM_palette_far = pgm_get_far_address(wi_wind_beaufort_10_RLEBM_palette);
bmInfo.width = 125;
bmInfo.height = 125;
bmInfo.flags = 0x01;
}
| C | CL | 18ae49f8c54d3c1329fd2b46e9bd227f96e83c164167760fafb34123b9c7a529 |
/* binary tree */
#include "include/vr_bitree.h"
#include "include/vr_stack.h"
vr_bitree_nd* vr_bitree_nd_new();
void vr_bitree_nd_des(vr_bitree_nd* nd,vr_kv_des_func des);
void vr_bitree_nd_set(vr_bitree_nd* nd,void* key,void* val);
void vr_bitree_nd_get(vr_bitree_nd* nd,void** key,void** val);
void vr_bitree_get_tglt(vr_bitree_nd* root,void* key,vr_bitree_nd** gra_nd,vr_bitree_nd** par_nd,vr_bitree_nd** nd,vr_compare_func comp);
void vr_bitree_pre_order(vr_bitree_nd* root,vr_trav_func hook);
void vr_bitree_in_order(vr_bitree_nd* root,vr_trav_func hook);
void vr_bitree_post_order(vr_bitree_nd* root,vr_trav_func hook);
vr_bitree* vr_bitree_new(vr_compare_func comp)
{
vr_bitree* tree=malloc(sizeof(vr_bitree));
if(tree!=NULL){
VR_BITREE_INIT(tree,comp);
}
return tree;
}
void vr_bitree_des(vr_bitree* tree,vr_kv_des_func des)
{
vr_bitree_cln(tree,des);
free(tree);
}
int vr_bitree_ins(vr_bitree* tree,void* key,void* val)
{
vr_bitree_nd* par_nd=NULL;
vr_bitree_nd* nd=NULL;
if(key==NULL||val==NULL){
return -1;
}
vr_bitree_get_tglt(tree->root,key,NULL,&par_nd,&nd,tree->comp);
if(nd)
return -1;
else{
nd=vr_bitree_nd_new();
vr_bitree_nd_set(nd,key,val);
if(par_nd==NULL)
tree->root=nd;
else{
int cmp=(* tree->comp)(key,par_nd->key);
if(cmp>0)
par_nd->right=nd;
else
par_nd->left=nd;
}
tree->size++;
}
return tree->size;
}
void* vr_bitree_get(vr_bitree* tree,void* key)
{
vr_bitree_nd* nd=NULL;
void* val=NULL;
vr_bitree_get_tglt(tree->root,key,NULL,NULL,&nd,tree->comp);
if(nd!=NULL)
vr_bitree_nd_get(nd,NULL,&val);
return val;
}
void vr_bitree_trav(vr_bitree* tree,vr_trav_func hook,int order)
{
switch(order){
case VR_TREE_PRE_ORDER_TRAV:vr_bitree_pre_order(tree->root,hook);break;
case VR_TREE_IN_ORDER_TRAV:vr_bitree_in_order(tree->root,hook);break;
case VR_TREE_POST_ORDER_TRAV:vr_bitree_post_order(tree->root,hook);break;
}
}
void vr_bitree_del(vr_bitree* tree,void* key,vr_kv_des_func des)
{
vr_bitree_nd* nd=NULL;
vr_bitree_nd* del_nd=NULL;
vr_bitree_nd* par_del_nd=NULL;
vr_bitree_nd* mv_nd=NULL;
vr_bitree_get_tglt(tree->root,key,NULL,&par_del_nd,&nd,tree->comp);
if(nd==NULL) return;
if(nd->left==NULL||nd->right==NULL)
del_nd=nd;
else
vr_bitree_get_tglt(nd->right,key,&par_del_nd,&del_nd,NULL,tree->comp);
if(del_nd->left)
mv_nd=del_nd->left;
else
mv_nd=del_nd->right;
if(par_del_nd==NULL)
tree->root=mv_nd;
else
if(par_del_nd->left==del_nd)
par_del_nd->left=mv_nd;
else
par_del_nd->right=mv_nd;
if(del_nd!=nd){
void* key=NULL;
void* val=NULL;
vr_bitree_nd_get(del_nd,&key,&val);
vr_bitree_nd_set(nd,key,val);
}
vr_bitree_nd_des(del_nd,des);
tree->size--;
}
static int vr_compare_alway_eq(void* max,void* min){return 0;}
void vr_bitree_cln(vr_bitree* tree,vr_kv_des_func des)
{
vr_bitree_nd* del_nd=NULL;
while(1){
vr_bitree_get_tglt(tree->root,NULL,NULL,NULL,&del_nd,vr_compare_alway_eq);
if(del_nd==NULL) break;
vr_bitree_del(tree,del_nd->key,des);
}
}
int vr_bitree_size(vr_bitree* tree)
{
return tree->size;
}
void vr_bitree_pre_order(vr_bitree_nd* root,vr_trav_func hook)
{
vr_bitree_nd* nd=root;
vr_bitree_nd* tmp_nd=NULL;
vr_stack* stk=vr_stack_new();
do{
if(nd){
if(nd->right) vr_stack_push(stk,nd->right);
tmp_nd=nd;nd=nd->left;
if((*hook)(tmp_nd->key,tmp_nd->val)==-1) break;
}else{
if(vr_stack_size(stk))
nd=vr_stack_pop(stk,NULL);
else
break;
}
} while(1);
vr_stack_des(stk,NULL);
}
void vr_bitree_in_order(vr_bitree_nd* root,vr_trav_func hook)
{
vr_bitree_nd* nd=root;
vr_bitree_nd* tmp_nd=NULL;
vr_stack* stk=vr_stack_new();
do{
if(nd){
vr_stack_push(stk,(void*)nd);
nd=nd->left;
} else {
if(vr_stack_size(stk)){
tmp_nd=vr_stack_pop(stk,NULL);
nd=tmp_nd->right;
if((*hook)(tmp_nd->key,tmp_nd->val)==-1) break;
} else{
break;
}
}
} while(1);
vr_stack_des(stk,NULL);
}
void vr_bitree_post_order(vr_bitree_nd* root,vr_trav_func hook)
{
vr_bitree_nd* nd=root;
vr_bitree_nd* tmp_nd=NULL;
vr_stack* stk=vr_stack_new();
do{
if(nd){
vr_bitree_nd* l=nd->left;
vr_bitree_nd* r=nd->right;
if( (l==NULL&&r==NULL) || (l==tmp_nd&&r==NULL) || r==tmp_nd ){
if((*hook)(nd->key,nd->val)==-1) break;
tmp_nd=nd;
}else{
vr_stack_push(stk,nd);
if(r)vr_stack_push(stk,r);
nd=l;
continue;
}
}
if(vr_stack_size(stk))
nd=vr_stack_pop(stk,NULL);
else
break;
} while(1);
vr_stack_des(stk,NULL);
}
void vr_bitree_get_tglt(vr_bitree_nd* root,void* key,vr_bitree_nd** gra_nd,vr_bitree_nd** par_nd,vr_bitree_nd** nd,vr_compare_func comp)
{
vr_bitree_nd* _gra_nd=NULL;
vr_bitree_nd* _par_nd=NULL;
vr_bitree_nd* _nd=root;
while(_nd!=NULL){
int cmp=(* comp)(key,_nd->key);
if(cmp==0){
break;
}else{
_gra_nd=_par_nd;
_par_nd=_nd;
if(cmp>0)
_nd=_nd->right;
else
_nd=_nd->left;
}
}
if(gra_nd!=NULL) *gra_nd=_gra_nd;
if(par_nd!=NULL) *par_nd=_par_nd;
if(nd!=NULL) *nd=_nd;
}
vr_bitree_nd* vr_bitree_nd_new()
{
vr_bitree_nd* nd=(vr_bitree_nd*) malloc(sizeof(vr_bitree_nd));
if(nd)
VR_BITREE_ND_INIT(nd);
return nd;
}
void vr_bitree_nd_des(vr_bitree_nd* nd,vr_kv_des_func des)
{
if(des)
des(nd->key,nd->val);
free(nd);
}
void vr_bitree_nd_set(vr_bitree_nd* nd,void* key,void* val)
{
if(key) nd->key=key;
if(val) nd->val=val;
}
void vr_bitree_nd_get(vr_bitree_nd* nd,void** key,void** val)
{
if(key) *key=nd->key;
if(val) *val=nd->val;
}
| C | CL | 9171f2cbbc69cdc45d14c48710a0cd3cb1a954bbc0696d376131c68446e0a0ac |
#include "json.h"
/*
*/
unsigned int json_decode_array(json_t *parent, char *p)
{
char *f = p + 1;
json_t *j = connect(parent);
j->type = ARRAY;
while(*f != ']') {
f += skip_whitespace(f);
switch((char)*f) {
case '[':
f += json_decode_array(j, f);
break;
case '{':
/* Object */
f += json_decode_object(j, f);
break;
case '"':
f += json_decode_string(j, f);
break;
case 't':
case 'f':
f += json_decode_bool(j, f);
break;
case 'n':
f += json_decode_null(j, f);
break;
case ',': /* Delimeter */
++f;
break;
default:
f += json_decode_number(j, f);
break;
}
f += skip_whitespace(f);
}
return (unsigned int)((f - p) + 1);
}
/*
*/
unsigned int json_decode_object(json_t *parent, char *p)
{
char *f = p + 1;
json_t *j = connect(parent);
j->type = OBJECT;
while(*f != '}') {
f += skip_whitespace(f);
switch((char)*f) {
case ',': /* Delimeter */
++f;
break;
default:
f += json_decode_pair(j, f);
break;
}
f += skip_whitespace(f);
}
return (unsigned int)((f - p) + 1);
}
/*
*/
unsigned int json_decode_pair(json_t *parent, char *p)
{
/* Get string : value */
char *f = p;
json_t *j = connect(parent);
j->type = PAIR;
/* TODO: error checking that a valid pair is presented */
while((*f != ':') && (*f != ' ') && (*f != '\t')) {
++f;
}
if(*p == '"') {
char *n = (char *)calloc((f - p) - 1, sizeof(char));
strncpy(n, (p + 1), (f - (p + 2)));
j->name = n;
}
else {
char *n = (char *)calloc((f - p) + 1, sizeof(char));
strncpy(n, p, (f - p));
j->name = n;
}
f += skip_whitespace(f);
/* Should then be ':' char */
if((char)*f == ':') {
++f;
}
else {
fprintf(error, "Object error, expecting ':' got '%c'\n", (char)*f);
}
f += skip_whitespace(f);
/* figure type of element */
switch((char)*f) {
case '[':
f += json_decode_array(j, f);
break;
case '{':
f += json_decode_object(j, f);
break;
case ',': /* Delimiter */
++f;
break;
case 't':
case 'f':
f += json_decode_bool(j, f);
break;
case 'n':
f += json_decode_null(j, f);
break;
case '"':
f += json_decode_string(j, f);
break;
default:
f += json_decode_number(j, f);
break;
}
f += skip_whitespace(f);
return (unsigned int)(f - p);
}
/*
Number
integer, float or double
generate a new json_t, include data and connect to parent json_t
*/
unsigned int json_decode_number(json_t *parent, char *p)
{
char *f = p;
json_t *j = connect(parent);
j->type = NUMBER;
while((*f != ',') && (*f != ']') && (*f != '}')) {
++f;
}
{
unsigned char type = INTEGER;
number_t *n = (number_t *)&(j->value.num);
char *i = (char *)calloc((f - p) + 1, sizeof(char));
strncpy(i, p, (f - p));
/* Check for type: integer, real or float */
if(strchr(i, (int)'.') != NULL) {
type = FLOAT;
}
if((strchr(i, (int)'e') || strchr(i, (int)'E'))) {
type = REAL;
}
/* Dependent on the type create a new instance of number */
switch(type) {
case INTEGER:
{
/* Convert from string to int */
n->value.ival = atoi(i);
n->type = INTEGER;
}
break;
case FLOAT:
{
/* Convert from string to float */
sscanf(i, "%f", &(n->value.fval));
n->type = FLOAT;
}
break;
case REAL:
{
sscanf(i, "%lf", &(n->value.dval));
n->type = REAL;
}
break;
default:
{
fprintf(error, "Unknown number type (%d)\n", type);
}
break;
}
free(i);
}
return (unsigned int)(f - p);
}
/*
*/
unsigned int json_decode_string(json_t *parent,char *p)
{
unsigned char escaped = 0;
char *f = (p + 1);
json_t *j = connect(parent);
j->type = STRING;
/* Loop through string, find end " */
/* Take into account escaped " */
while((*f != '"') || escaped) {
if(escaped) { escaped = 0; }
if(*f == '\\') { escaped = 1; }
++f;
}
f += 1;
{
/* Ignore leading and trailing " characters */
char *s = (char *)calloc((f - p) - 1, sizeof(char));
strncpy(s, (p + 1), (f - (p + 2)));
j->value.str = s;
}
return (unsigned int)(f - p);
}
/*
*/
unsigned int json_decode_null(json_t *parent, char *p)
{
char *f = p;
json_t *j = connect(parent);
j->type = STRING;
while((*f != ',') && (*f != ']') && (*f != '}')) {
++f;
}
if(!strncmp(p, "null", 4)) {
j->value.str = NULL;
}
else {
fprintf(error, "Unknown NULL type (%s)\n", p);
exit(-1);
}
return (unsigned int)(f - p);
}
/*
Bool
true or false
*/
unsigned int json_decode_bool(json_t *parent, char *p)
{
char *f = p;
json_t *j = connect(parent);
j->type = BOOL;
while((*f != ',') && (*f != ']') && (*f != '}')) {
++f;
}
if(!strncmp(p, "true", 4)) {
j->value.bool = 1;
}
else if(!strncmp(p, "false", 5)) {
j->value.bool = 0;
}
else {
fprintf(error, "Unknown BOOL type (%s)\n", p);
exit(-1);
}
return (unsigned int)(f - p);
}
/*
Connect j to parent.
if content is null this is the first item otherwise it is part of a list
*/
json_t *connect(json_t *parent)
{
if(parent->content == NULL) {
parent->content = (json_t *)calloc(1, sizeof(json_t));
if(parent->content == NULL) {
fprintf(error, "Memory allocation error (calloc)\n");
exit(-1);
}
++parent->num;
return (json_t *)parent->content;
}
else {
++parent->num;
parent->content = (json_t *)realloc(parent->content, sizeof(json_t) * parent->num);
if(parent->content == NULL) {
fprintf(error, "Memory allocation error (realloc)\n");
exit(-1);
}
{
json_t *temp = (json_t *)(parent->content + (parent->num - 1));
temp->content = NULL;
temp->num = 0;
}
return (json_t *)(parent->content + (parent->num - 1));
}
return (json_t *)NULL;
}
unsigned int skip_whitespace(char *p)
{
char *f = p;
while((*f == ' ') || (*f == '\t') || (*f == '\n')) {
++f;
}
return (unsigned int)(f - p);
}
| C | CL | 9fd198439959e536707e739a85ffdfaa7000f872489b8aee6e0fe326659ad4e4 |
#pragma once
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// -------- タッチ処理
// タッチ識別ID列挙型
enum engineCtrlTouchId{
ENGINECTRLTOUCHID_NONE,
ENGINECTRLTOUCHID_TEST1,
ENGINECTRLTOUCHID_TEST2,
ENGINECTRLTOUCHID_CONTROLLER,
ENGINECTRLTOUCHID_BUTTON,
ENGINECTRLTOUCHID_SCREEN,
};
// タッチ状態構造体
struct engineCtrlTouch{
// タッチID
enum engineCtrlTouchId touchId;
// ウインドウ内位置
struct{
int x;
int y;
} window;
// スクリーン内位置
struct{
int x;
int y;
} screen;
// 押下中フラグ
bool dn;
// 移動中フラグ
bool mv;
// 占有中フラグ
bool active;
};
// ----------------------------------------------------------------
// コントローラ状態メインループ計算
void engineCtrlTouchCalc(void);
// タッチ情報取得
struct engineCtrlTouch *engineCtrlTouchGet(enum engineCtrlTouchId touchId);
// 取得したタッチ情報占有
void engineCtrlTouchOwn(void);
// 取得して占有したタッチ情報の解放
void engineCtrlTouchFree(void);
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
| C | CL | ebdbe57c845fb10c6e7c5937ea2c8c09cbda5f92beb597acb1f5afda81cd86c5 |
#include "async.h"
#include "tame.h"
#pragma once
extern int dsdc_heartbeat_interval;
extern int dsdcs_getstate_interval;
extern int dsdc_missed_beats_to_death;
extern int dsdc_port;
extern int dsdc_proxy_port;
extern int dsdc_slave_port;
extern int dsdc_retry_wait_time;
extern u_int dsdc_rpc_timeout;
extern u_int dsdc_slave_nnodes;
extern size_t dsdc_slave_maxsz;
extern u_int dsdc_packet_sz;
extern u_int dsdcs_port_attempts;
extern u_int dsdcl_default_timeout;
extern time_t dsdci_connect_timeout_ms;
extern time_t dsdcm_timer_interval;
extern int dsdc_aiod2_remote_port;
extern size_t dsdcs_clean_batch;
extern time_t dsdcs_clean_wait_us;
typedef event<int,str>::ref evis_t;
| C | CL | f2d7076fba42b6ad60923f5ca22b1e9333f6bd3456d5bbeb44d0c9b577844c97 |
/*
* Copyright (c) 2014-2016, dennis wang
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "buffer.h"
#include "logger.h"
/**
* 发送缓冲区
*/
struct _buffer_t {
char* m; /* 地址指针 */
char* ptr; /* 缓冲区起始地址 */
uint32_t len; /* 缓冲区长度 */
uint32_t pos; /* 缓冲区当前位置 */
};
kbuffer_t* knet_buffer_create(uint32_t size) {
kbuffer_t* sb = knet_create(kbuffer_t);
verify(sb);
if (!sb) {
return 0;
}
/* 数据指针 */
sb->ptr = knet_create_raw(size);
verify(sb->ptr);
if (!sb->ptr) {
knet_buffer_destroy(sb);
return 0;
}
sb->m = sb->ptr;
sb->pos = 0;
sb->len = size;
return sb;
}
void knet_buffer_destroy(kbuffer_t* sb) {
verify(sb);
if (!sb) {
return;
}
if (sb->m) {
knet_free(sb->m);
}
if (sb) {
knet_free(sb);
}
}
uint32_t knet_buffer_put(kbuffer_t* sb, const char* temp, uint32_t size) {
verify(sb);
verify(temp);
verify(size);
if (!sb || !temp || !size) {
return 0;
}
if (size > sb->len - sb->pos) {
return 0;
}
memcpy(sb->ptr + sb->pos, temp, size);
sb->pos += size;
return size;
}
uint32_t knet_buffer_get_length(kbuffer_t* sb) {
verify(sb);
if (!sb) {
return 0;
}
return sb->pos;
}
uint32_t knet_buffer_get_max_size(kbuffer_t* sb) {
verify(sb);
if (!sb) {
return 0;
}
return sb->len;
}
int knet_buffer_enough(kbuffer_t* sb, uint32_t size) {
verify(sb);
if (!sb) {
return 0;
}
return (sb->pos + size > sb->len);
}
char* knet_buffer_get_ptr(kbuffer_t* sb) {
verify(sb);
if (!sb) {
return 0;
}
return sb->ptr;
}
void knet_buffer_adjust(kbuffer_t* sb, uint32_t gap) {
verify(sb); /* gap可以为0 */
if (!sb) {
return;
}
sb->ptr += gap;
sb->pos -= gap;
}
void knet_buffer_clear(kbuffer_t* sb) {
verify(sb);
if (!sb) {
return;
}
if (!sb->ptr) {
return;
}
sb->ptr = sb->m;
sb->pos = 0;
}
| C | CL | 55fc6d5de4a152c3f30229e712677435890d966d6d5432fc360c86a56d192938 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.