/// destroys the given socket void net_wiznet_closesocket(JsNetwork *net, int sckt) { NOT_USED(net); // try and close gracefully disconnect((uint8_t)sckt); JsSysTime timeout = jshGetSystemTime()+jshGetTimeFromMilliseconds(1000); uint8_t status; while ((status=getSn_SR((uint8_t)sckt)) != SOCK_CLOSED && jshGetSystemTime()<timeout) ; // if that didn't work, force it if (status != SOCK_CLOSED) closesocket((uint8_t)sckt); // Wiznet is a bit strange in that it uses the same socket for server and client if (sckt & WIZNET_SERVER_CLIENT) { // so it's just closed, but put it into 'listen' mode again sckt = socket((uint8_t)sckt, Sn_MR_TCP, wiznetSocketPorts[sckt&7], SF_IO_NONBLOCK); listen((uint8_t)sckt); // Be sure to mark it as not a client socket any more wiznetSocketAsServerClient = wiznetSocketAsServerClient & (unsigned char)~(1<<(sckt&7)); } }
/*JSON{ "type":"function", "name" : "setTimeout", "description" : ["Call the function specified ONCE after the timeout in milliseconds.", "The function that is being called may also take an argument, which is an object containing a field called 'time' (the time in seconds at which the timer happened)", "for example: ```setTimeout(function (e) { print(e.time); }, 1000);```", "This can also be removed using clearTimeout", "**Note:** If `setDeepSleep(true)` has been called and the interval is greater than 5 seconds, Espruino may execute the interval up to 1 second late. This is because Espruino can only wake from deep sleep every second - and waking early would cause Espruino to waste power while it waited for the correct time." ], "generate" : "jswrap_interface_setTimeout", "params" : [ [ "function", "JsVar", "A Function or String to be executed"], [ "timeout", "float", "The time until the function will be executed" ] ], "return" : ["JsVar", "An ID that can be passed to clearTimeout"] }*/ JsVar *_jswrap_interface_setTimeoutOrInterval(JsVar *func, JsVarFloat interval, bool isTimeout) { // NOTE: The 5 sec delay mentioned in the description is handled by jshSleep JsVar *itemIndex = 0; if (!jsvIsFunction(func) && !jsvIsString(func)) { jsError("Function or String not supplied!"); } else { // Create a new timer JsVar *timerPtr = jsvNewWithFlags(JSV_OBJECT); if (interval<TIMER_MIN_INTERVAL) interval=TIMER_MIN_INTERVAL; JsVarInt intervalInt = jshGetTimeFromMilliseconds(interval); jsvUnLock(jsvObjectSetChild(timerPtr, "time", jsvNewFromInteger(jshGetSystemTime() + intervalInt))); jsvUnLock(jsvObjectSetChild(timerPtr, "interval", jsvNewFromInteger(intervalInt))); if (!isTimeout) jsvUnLock(jsvObjectSetChild(timerPtr, "recur", jsvNewFromBool(true))); jsvObjectSetChild(timerPtr, "callback", func); // intentionally no unlock // Add to array itemIndex = jsvNewFromInteger(jsiTimerAdd(timerPtr)); jsvUnLock(timerPtr); } return itemIndex; }
void jshPinPulse(Pin pin, bool pulsePolarity, JsVarFloat pulseTime) { // ---- USE TIMER FOR PULSE if (!jshIsPinValid(pin)) { jsExceptionHere(JSET_ERROR, "Invalid pin!"); return; } if (pulseTime<=0) { // just wait for everything to complete jstUtilTimerWaitEmpty(); return; } else { // find out if we already had a timer scheduled UtilTimerTask task; if (!jstGetLastPinTimerTask(pin, &task)) { // no timer - just start the pulse now! jshPinOutput(pin, pulsePolarity); task.time = jshGetSystemTime(); } // Now set the end of the pulse to happen on a timer jstPinOutputAtTime(task.time + jshGetTimeFromMilliseconds(pulseTime), &pin, 1, !pulsePolarity); } }
/*JSON{ "type" : "function", "name" : "changeInterval", "generate" : "jswrap_interface_changeInterval", "params" : [ ["id","JsVar","The id returned by a previous call to setInterval"], ["time","float","The new time period in ms"] ] } Change the Interval on a callback created with setInterval, for example: ```var id = setInterval(function () { print('foo'); }, 1000); // every second``` ```changeInterval(id, 1500); // now runs every 1.5 seconds``` This takes effect the next time the callback is called (so it is not immediate). */ void jswrap_interface_changeInterval(JsVar *idVar, JsVarFloat interval) { JsVar *timerArrayPtr = jsvLock(timerArray); if (interval<TIMER_MIN_INTERVAL) interval=TIMER_MIN_INTERVAL; JsVar *timerName = jsvIsBasic(idVar) ? jsvFindChildFromVar(timerArrayPtr, idVar, false) : 0; if (timerName) { JsVar *timer = jsvSkipNameAndUnLock(timerName); JsVar *v; JsVarInt intervalInt = (JsVarInt)jshGetTimeFromMilliseconds(interval); v = jsvNewFromInteger(intervalInt); jsvUnLock(jsvSetNamedChild(timer, v, "interval")); jsvUnLock(v); v = jsvNewFromInteger((JsVarInt)(jshGetSystemTime()-jsiLastIdleTime) + intervalInt); jsvUnLock(jsvSetNamedChild(timer, v, "time")); jsvUnLock(v); jsvUnLock(timer); // timerName already unlocked jsiTimersChanged(); // mark timers as changed } else { jsExceptionHere(JSET_ERROR, "Unknown Interval"); } jsvUnLock(timerArrayPtr); }
/*JSON{ "type" : "function", "name" : "setTimeout", "generate" : "jswrap_interface_setTimeout", "params" : [ ["function","JsVar","A Function or String to be executed"], ["timeout","float","The time until the function will be executed"] ], "return" : ["JsVar","An ID that can be passed to clearTimeout"] } Call the function specified ONCE after the timeout in milliseconds. The function that is being called may also take an argument, which is an object containing a field called 'time' (the time in seconds at which the timer happened) for example: ```setTimeout(function (e) { print(e.time); }, 1000);``` This can also be removed using clearTimeout **Note:** If `setDeepSleep(true)` has been called and the interval is greater than 5 seconds, Espruino may execute the interval up to 1 second late. This is because Espruino can only wake from deep sleep every second - and waking early would cause Espruino to waste power while it waited for the correct time. */ JsVar *_jswrap_interface_setTimeoutOrInterval(JsVar *func, JsVarFloat interval, bool isTimeout) { // NOTE: The 5 sec delay mentioned in the description is handled by jshSleep JsVar *itemIndex = 0; if (!jsvIsFunction(func) && !jsvIsString(func)) { jsExceptionHere(JSET_ERROR, "Function or String not supplied!"); } else { // Create a new timer JsVar *timerPtr = jsvNewWithFlags(JSV_OBJECT); if (interval<TIMER_MIN_INTERVAL) interval=TIMER_MIN_INTERVAL; JsSysTime intervalInt = jshGetTimeFromMilliseconds(interval); //jsiConsolePrintf("interval = %f,intervalInt = %d,now = %d,timeInt = %d\n",interval,intervalInt,jshGetSystemTime(),(jshGetSystemTime() - jsiLastIdleTime) + intervalInt); jsvUnLock(jsvObjectSetChild(timerPtr, "time", jsvNewFromLongInteger((jshGetSystemTime() - jsiLastIdleTime) + intervalInt))); if (!isTimeout) { jsvUnLock(jsvObjectSetChild(timerPtr, "interval", jsvNewFromLongInteger(intervalInt))); } jsvObjectSetChild(timerPtr, "callback", func); // intentionally no unlock // Add to array itemIndex = jsvNewFromInteger(jsiTimerAdd(timerPtr)); jsvUnLock(timerPtr); } return itemIndex; }
unsigned char * hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen) { unsigned char *pucReceivedData, ucArgsize; unsigned short usLength; unsigned char *pucReceivedParams; unsigned short usReceivedEventOpcode = 0; unsigned long retValue32; unsigned char * RecvParams; unsigned char *RetParams; JsSysTime timeout = jshGetSystemTime() + jshGetTimeFromMilliseconds(10000); // blocking for 10 seconds (!!!) cc3000_irq_disable(); while (!jspIsInterrupted()) { if (tSLInformation.usEventOrDataReceived != 0) { pucReceivedData = (tSLInformation.pucReceivedData); if (*pucReceivedData == HCI_TYPE_EVNT) { // Event Received STREAM_TO_UINT16((char *)pucReceivedData, HCI_EVENT_OPCODE_OFFSET, usReceivedEventOpcode); pucReceivedParams = pucReceivedData + HCI_EVENT_HEADER_SIZE; RecvParams = pucReceivedParams; RetParams = pRetParams; // In case unsolicited event received - here the handling finished if (hci_unsol_event_handler((char *)pucReceivedData) == 0) { STREAM_TO_UINT8(pucReceivedData, HCI_DATA_LENGTH_OFFSET, usLength); switch(usReceivedEventOpcode) { case HCI_CMND_READ_BUFFER_SIZE: { STREAM_TO_UINT8((char *)pucReceivedParams, 0, tSLInformation.usNumberOfFreeBuffers); STREAM_TO_UINT16((char *)pucReceivedParams, 1, tSLInformation.usSlBufferLength); } break; case HCI_CMND_WLAN_CONFIGURE_PATCH: case HCI_NETAPP_DHCP: case HCI_NETAPP_PING_SEND: case HCI_NETAPP_PING_STOP: case HCI_NETAPP_ARP_FLUSH: case HCI_NETAPP_SET_DEBUG_LEVEL: case HCI_NETAPP_SET_TIMERS: case HCI_EVNT_NVMEM_READ: case HCI_EVNT_NVMEM_CREATE_ENTRY: case HCI_CMND_NVMEM_WRITE_PATCH: case HCI_NETAPP_PING_REPORT: case HCI_EVNT_MDNS_ADVERTISE: STREAM_TO_UINT8(pucReceivedData, HCI_EVENT_STATUS_OFFSET ,*(unsigned char *)pRetParams); break; case HCI_CMND_SETSOCKOPT: case HCI_CMND_WLAN_CONNECT: case HCI_CMND_WLAN_IOCTL_STATUSGET: case HCI_EVNT_WLAN_IOCTL_ADD_PROFILE: case HCI_CMND_WLAN_IOCTL_DEL_PROFILE: case HCI_CMND_WLAN_IOCTL_SET_CONNECTION_POLICY: case HCI_CMND_WLAN_IOCTL_SET_SCANPARAM: case HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_START: case HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_STOP: case HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_SET_PREFIX: case HCI_CMND_EVENT_MASK: case HCI_EVNT_WLAN_DISCONNECT: case HCI_EVNT_SOCKET: case HCI_EVNT_BIND: case HCI_CMND_LISTEN: case HCI_EVNT_CLOSE_SOCKET: case HCI_EVNT_CONNECT: case HCI_EVNT_NVMEM_WRITE: STREAM_TO_UINT32((char *)pucReceivedParams,0 ,*(unsigned long *)pRetParams); break; case HCI_EVNT_READ_SP_VERSION: STREAM_TO_UINT8(pucReceivedData, HCI_EVENT_STATUS_OFFSET ,*(unsigned char *)pRetParams); pRetParams = ((char *)pRetParams) + 1; STREAM_TO_UINT32((char *)pucReceivedParams, 0, retValue32); UINT32_TO_STREAM((unsigned char *)pRetParams, retValue32); break; case HCI_EVNT_BSD_GETHOSTBYNAME: STREAM_TO_UINT32((char *)pucReceivedParams ,GET_HOST_BY_NAME_RETVAL_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; STREAM_TO_UINT32((char *)pucReceivedParams ,GET_HOST_BY_NAME_ADDR_OFFSET,*(unsigned long *)pRetParams); break; case HCI_EVNT_ACCEPT: { STREAM_TO_UINT32((char *)pucReceivedParams,ACCEPT_SD_OFFSET ,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; STREAM_TO_UINT32((char *)pucReceivedParams ,ACCEPT_RETURN_STATUS_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; //This argument returns in network order memcpy((unsigned char *)pRetParams, pucReceivedParams + ACCEPT_ADDRESS__OFFSET, sizeof(sockaddr)); break; } case HCI_EVNT_RECV: case HCI_EVNT_RECVFROM: { STREAM_TO_UINT32((char *)pucReceivedParams,SL_RECEIVE_SD_OFFSET ,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; STREAM_TO_UINT32((char *)pucReceivedParams,SL_RECEIVE_NUM_BYTES_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; STREAM_TO_UINT32((char *)pucReceivedParams,SL_RECEIVE__FLAGS__OFFSET,*(unsigned long *)pRetParams); if(((tBsdReadReturnParams *)pRetParams)->iNumberOfBytes == ERROR_SOCKET_INACTIVE) { set_socket_active_status(((tBsdReadReturnParams *)pRetParams)->iSocketDescriptor,SOCKET_STATUS_INACTIVE); } break; } case HCI_EVNT_SEND: case HCI_EVNT_SENDTO: { STREAM_TO_UINT32((char *)pucReceivedParams,SL_RECEIVE_SD_OFFSET ,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; STREAM_TO_UINT32((char *)pucReceivedParams,SL_RECEIVE_NUM_BYTES_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; break; } case HCI_EVNT_SELECT: { STREAM_TO_UINT32((char *)pucReceivedParams,SELECT_STATUS_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; STREAM_TO_UINT32((char *)pucReceivedParams,SELECT_READFD_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; STREAM_TO_UINT32((char *)pucReceivedParams,SELECT_WRITEFD_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; STREAM_TO_UINT32((char *)pucReceivedParams,SELECT_EXFD_OFFSET,*(unsigned long *)pRetParams); break; } case HCI_CMND_GETSOCKOPT: STREAM_TO_UINT8(pucReceivedData, HCI_EVENT_STATUS_OFFSET,((tBsdGetSockOptReturnParams *)pRetParams)->iStatus); //This argument returns in network order memcpy((unsigned char *)pRetParams, pucReceivedParams, 4); break; case HCI_CMND_WLAN_IOCTL_GET_SCAN_RESULTS: STREAM_TO_UINT32((char *)pucReceivedParams,GET_SCAN_RESULTS_TABlE_COUNT_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; STREAM_TO_UINT32((char *)pucReceivedParams,GET_SCAN_RESULTS_SCANRESULT_STATUS_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 4; STREAM_TO_UINT16((char *)pucReceivedParams,GET_SCAN_RESULTS_ISVALID_TO_SSIDLEN_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 2; STREAM_TO_UINT16((char *)pucReceivedParams,GET_SCAN_RESULTS_FRAME_TIME_OFFSET,*(unsigned long *)pRetParams); pRetParams = ((char *)pRetParams) + 2; memcpy((unsigned char *)pRetParams, (char *)(pucReceivedParams + GET_SCAN_RESULTS_FRAME_TIME_OFFSET + 2), GET_SCAN_RESULTS_SSID_MAC_LENGTH); break; case HCI_CMND_SIMPLE_LINK_START: break; case HCI_NETAPP_IPCONFIG: //Read IP address STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH); RecvParams += 4; //Read subnet STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH); RecvParams += 4; //Read default GW STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH); RecvParams += 4; //Read DHCP server STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH); RecvParams += 4; //Read DNS server STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH); RecvParams += 4; //Read Mac address STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_MAC_LENGTH); RecvParams += 6; //Read SSID STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_SSID_LENGTH); } } if (usReceivedEventOpcode == tSLInformation.usRxEventOpcode) { tSLInformation.usRxEventOpcode = 0; } } else { pucReceivedParams = pucReceivedData; STREAM_TO_UINT8((char *)pucReceivedData, HCI_PACKET_ARGSIZE_OFFSET, ucArgsize); STREAM_TO_UINT16((char *)pucReceivedData, HCI_PACKET_LENGTH_OFFSET, usLength); // Data received: note that the only case where from and from length // are not null is in recv from, so fill the args accordingly if (from) { STREAM_TO_UINT32((char *)(pucReceivedData + HCI_DATA_HEADER_SIZE), BSD_RECV_FROM_FROMLEN_OFFSET, *(unsigned long *)fromlen); memcpy(from, (pucReceivedData + HCI_DATA_HEADER_SIZE + BSD_RECV_FROM_FROM_OFFSET) ,*fromlen); } if (pRetParams) // GW: just in case. It'll probably still crash though :( memcpy(pRetParams, pucReceivedParams + HCI_DATA_HEADER_SIZE + ucArgsize, usLength - ucArgsize); tSLInformation.usRxDataPending = 0; } tSLInformation.usEventOrDataReceived = 0; cc3000_spi_resume(); // Since we are going to TX - we need to handle this event after the // ResumeSPi since we need interrupts if ((*pucReceivedData == HCI_TYPE_EVNT) && (usReceivedEventOpcode == HCI_EVNT_PATCHES_REQ)) { hci_unsol_handle_patch_request((char *)pucReceivedData); } if ((tSLInformation.usRxEventOpcode == 0) && (tSLInformation.usRxDataPending == 0)) { cc3000_irq_enable(); return NULL; } } else cc3000_check_irq_pin(); if (jshGetSystemTime() > timeout) { jspSetInterrupted(true); jsError("Timeout in CC3000 driver (%d)", tSLInformation.usRxEventOpcode); break; } } cc3000_irq_enable(); return NULL; }
/*JSON{ "type":"method", "class": "Pin", "name" : "writeAtTime", "ifndef" : "SAVE_ON_FLASH", "description" : "Sets the output state of the pin to the parameter given at the specified time", "generate" : "jswrap_pin_writeAtTime", "params" : [ [ "value", "bool", "Whether to set output high (true/1) or low (false/0)"], ["time", "float", "Time at which to write"] ] }*/ void jswrap_pin_writeAtTime(JsVar *parent, bool value, JsVarFloat time) { Pin pin = jshGetPinFromVar(parent); JsSysTime sTime = jshGetTimeFromMilliseconds(time*1000); jstPinOutputAtTime(sTime, &pin, 1, value); }
/*JSON{ "type" : "function", "name" : "setTime", "generate" : "jswrap_interactive_setTime", "params" : [ ["time","float",""] ] } Set the current system time in seconds (to the nearest second) */ void jswrap_interactive_setTime(JsVarFloat time) { JsSysTime stime = jshGetTimeFromMilliseconds(time*1000); jsiLastIdleTime = stime; jshSetSystemTime(stime); }
/*JSON{ "type" : "staticmethod", "class" : "Date", "name" : "now", "generate" : "jswrap_date_now", "return" : ["float",""] } Get the number of milliseconds elapsed since 1970 (or on embedded platforms, since startup) */ JsVarFloat jswrap_date_now() { // Not quite sure why we need this, but (JsVarFloat)jshGetSystemTime() / (JsVarFloat)jshGetTimeFromMilliseconds(1) in inaccurate on STM32 return ((JsVarFloat)jshGetSystemTime() / (JsVarFloat)jshGetTimeFromMilliseconds(1000)) * 1000; }
/*JSON{ "type" : "staticmethod", "class" : "Trig", "name" : "getPosAtTime", "generate" : "jswrap_trig_getPosAtTime", "params" : [ ["time","float","The time at which to find the position"] ], "return" : ["float","The position of the trigger wheel in degrees - as a floating point number"] } Get the position of the trigger wheel at the given time (from getTime) */ JsVarFloat jswrap_trig_getPosAtTime(JsVarFloat time) { JsSysTime sTime = (JsSysTime)(time * (JsVarFloat)jshGetTimeFromMilliseconds(1000)); TriggerStruct *trig = &mainTrigger; JsVarFloat position = trigGetToothAtTime(trig, sTime); return wrapAround((position * 360 / trig->teethTotal) + trig->keyPosition, 360); }
/*JSON{ "type" : "staticmethod", "class" : "Trig", "name" : "getRPM", "generate" : "jswrap_trig_getRPM", "return" : ["float","The current RPM of the trigger wheel"] } Get the RPM of the trigger wheel */ JsVarFloat jswrap_trig_getRPM() { TriggerStruct *trig = &mainTrigger; if (jshGetSystemTime() > (trig->lastTime + trig->maxTooth)) return 0; return jshGetTimeFromMilliseconds(60000) / (JsVarFloat)(trig->avrTooth * trig->teethTotal); }
bool wice_msg_isTimeout(WiceMessage *msg){ JsVarFloat current = (JsVarFloat)jshGetSystemTime() / (JsVarFloat)jshGetTimeFromMilliseconds(1000); return (current > (msg->startTime + 20)); }
void wice_msg_start(WiceMessage *msg){ if (!msg->hasStarted){ msg->startTime = (JsVarFloat)jshGetSystemTime() / (JsVarFloat)jshGetTimeFromMilliseconds(1000); msg->hasStarted = true; } }